原型模式就是通过拷贝快速创建一个新的对象
本例UML如图
ColorBase
[Serializable]
public abstract class ColorBase
{
public int R = 0;
public int G = 0;
public int B = 0;
public virtual ColorBase Clone()
{
return this;
} public virtual void ShowMe()
{
Console.WriteLine(string.Format(" r={0} g={1} b={2}", R, G, B));
}
}
RGBAColor
[Serializable]
public class RGBAColor : ColorBase
{
public override ColorBase Clone()
{
ColorBase color;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
color = (RGBAColor)formatter.Deserialize(memoryStream);
return color;
}
}
ColorManager
public class ColorManager
{
RGBAColor rgbColor = new RGBAColor(); public ColorBase ColorBase
{
get
{
throw new System.NotImplementedException();
}
set
{
}
} public ColorBase GetNewColor()
{
return rgbColor.Clone();
}
}
Main方法中进行测试
static void Main(string[] args)
{
ColorManager colorManager = new ColorManager();
ColorBase red = colorManager.GetNewColor();
red.R = 255; ColorBase green = colorManager.GetNewColor();
green.G = 255; ColorBase blue = colorManager.GetNewColor();
blue.B = 255; red.ShowMe();
green.ShowMe();
blue.ShowMe(); Console.Read();
}
执行结果