Prototype Design Pattern

Introduction:
Sometimes we have a case where we want to build an object based on another object instead of creating a new fresh object each time, we can make a copy of an already existing object instantly and start using the new created object. By doing so, we do not have to repeat the building process each time. The newly created object will be independent from the old one.
We can use the Prototype Design Pattern to solve this issue.
Example:
On the following example we will create couple of color objects then Cline those objects into new instances.

PrototypeDesignPattern

 

abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}

class ColorManager
{
private Dictionary<string, ColorPrototype> _colors = new Dictionary<string, ColorPrototype>();
// Indexer
public ColorPrototype this[string key]
{
get { return _colors[key]; }
set { _colors.Add(key, value); }
}
}

class Color : ColorPrototype
{
private int _red;
private int _green;
private int _blue;
// Constructor
public Color(int red, int green, int blue)
{
this._red = red;
this._green = green;
this._blue = blue;
}
// Create a shallow copy
public override ColorPrototype Clone()
{
Console.WriteLine(
“Cloning color RGB: ” + _red.ToString() + ” , ” +
_green.ToString() + ” , ” + _blue.ToString());
return this.MemberwiseClone() as ColorPrototype;
}
}

static void Main(string[] args)
{
ColorManager colormanager = new ColorManager();
// Initialize with standard colors
colormanager[“RED”] = new Color(255, 0, 0);
colormanager[“GREEN”] = new Color(0, 255, 0);
colormanager[“BLUE”] = new Color(0, 0, 255);
// User adds personalized colors
colormanager[“ANGRY”] = new Color(255, 12, 0);
colormanager[“PEACE”] = new Color(128, 200, 128);
colormanager[“FLAME”] = new Color(211, 150, 20);
// User clones selected colors
Color color1 = colormanager[“RED”].Clone() as Color;
Color color2 = colormanager[“PEACE”].Clone() as Co  lor;
Color color3 = colormanager[“FLAME”].Clone() as Color;
// Wait for user
Console.ReadKey();
}

Download Code