设计模式学习之原型模式(Prototype)

作用:创建新对象时不需要重新定义类,直接从原型类里拷贝创建新对象
实现要点:克隆。(c#的克隆分为浅表拷贝和深度拷贝,详情参见msdn)
UML:

代码:(注:这段代码来自TerryLee  ,http://www.cnblogs.com/Terrylee/ ,觉得很好,顺便复习了索引器,就照搬了。)

abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
class Color : ColorPrototype
{
private int red, green, blue;
public Color(int red, int green, int blue)
{
this.red = red;
this.blue = blue;
this.green = green;
}
public override ColorPrototype Clone()
{
Console.WriteLine(
"Cloning color RGB: {0,3},{1,3},{2,3}", red, green, blue);
return this.MemberwiseClone() as ColorPrototype;
}
}
class ColorManager
{
Hashtable colors
= new Hashtable();
//indexer
public ColorPrototype this[string name]
{
get
{
return colors[name] as ColorPrototype;
}
set
{
colors.Add(name, value);
}
}
}
//---------------------执行-------------------------
class Program
{
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, 54, 0);
colormanager[
"peace"] = new Color(128, 211, 128);
colormanager[
"flame"] = new Color(211, 34, 20);
Color color;
// User uses selected colors
string name = "red";
color
= colormanager[name].Clone() as Color;
name
= "peace";
color
= colormanager[name].Clone() as Color;
name
= "flame";
color
= colormanager[name].Clone() as Color;
// Wait for user
Console.Read();
}
}
posted @ 2008-11-13 10:44  MichaelChen  阅读(287)  评论(0编辑  收藏  举报