The Prototype pattern creates new objects by cloning one of a few stored prototypes.
I desided to apply this pattern for a small application to sell different devices.
internal abstract class DevicePrototype
{
public abstract DevicePrototype Clone();
}
This class defines the interface that says prototypes must be cloneable. Now we need to create a class with cloning capabilities. In our situation it'll be class represented some device:
internal class Device: DevicePrototype
{
public Guid Guid { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Owner { get; set; }
public override DevicePrototype Clone()
{
Console.WriteLine("Cloning device - Name: {0}, Price: {1}",
Name, Price);
return MemberwiseClone() as DevicePrototype;
}
public override string ToString()
{
return string.Format("Guid:{0}\nName:{1}\nPrice{2}\nOwner{3}\n\n",
Guid, Name, Price, Owner);
}
}
Then we'll create prototype maneger. In our case we'll use this manager as shop to store devices for selling.
internal class DeviceManager
{
private Hashtable devices=new Hashtable();
public DevicePrototype this[string name]
{
get
{
return devices.ContainsKey(name)
? devices[name] as DevicePrototype
: null;
}
set
{
devices.Add(name, value);
}
}
}
And now is the time to play with created classes to demonstrate how we use Prototype pattern:
class Program
{
static void Main(string[] args)
{
var shop = new DeviceManager();
var devices = new List<Device>();
shop["iPhone"] = new Device {Guid = Guid.Empty,
Name = "iPhone", Price = 1000};
shop["iPad"] = new Device {Guid = Guid.Empty,
Name = "iPad", Price = 1200};
var iPhoneForDavid = shop["iPhone"].Clone() as Device;
iPhoneForDavid.Guid = Guid.NewGuid();
iPhoneForDavid.Owner = "David";
devices.Add(iPhoneForDavid);
var iPhoneForSara = shop["iPhone"].Clone() as Device;
iPhoneForSara.Guid = Guid.NewGuid();
iPhoneForSara.Owner = "Sara";
devices.Add(iPhoneForSara);
var iPodForSara = shop["iPad"].Clone() as Device;
iPodForSara.Guid = Guid.NewGuid();
iPodForSara.Owner = "Sara";
devices.Add(iPodForSara);
Console.WriteLine("\n\n\nShow all iPhones");
Console.WriteLine("----------------------------");
var iPhones = devices.Where(d => d.Name == "iPhone");
foreach (var iPhone in iPhones)
{
Console.Write(iPhone);
}
}
}