Net设计模式实例之原型模式( Prototype Pattern)(2)
四.原型模式实例分析(Example)
1、场景
颜色索引器存储多种颜色值,从颜色索引器中克隆客户需要几种颜色。结构如下图所示
ColorManager类:颜色索引器
ColorPrototype类:原型模式抽象类
Color类:原型模式抽象类的具体实现,Clone方法的实现,克隆自身的操作
2、代码
1、原型模式抽象类ColorPrototype及其具体实现类Color
|
/// <summary>
/// 原型模式抽象类
/// </summary>
public abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
/// <summary>
/// 具体实现类
/// </summary>
public class Color : ColorPrototype
{
private int _red;
private int _green;
private int _blue;
public Color(int red, int green, int blue)
{
this._red = red;
this._green = green;
this._blue = blue;
}
/// <summary>
/// 实现浅复制
/// </summary>
/// <returns></returns>
public override ColorPrototype Clone()
{
Console.WriteLine("Cloning color RGB: {0,3},{1,3},{2,3}", _red, _green, _blue);
return this.MemberwiseClone() as ColorPrototype;
}
}
|
3、客户端代码
|
static void Main(string[] args)
{
ColorManager colormanager = new ColorManager();
//初始化标准的red green blue颜色。
colormanager["red"] = new Color(255, 0, 0);
colormanager["green"] = new Color(0, 255, 0);
colormanager["blue"] = new Color(0, 0, 255);
// 添加个性的颜色
colormanager["angry"] = new Color(255, 54, 0);
colormanager["peace"] = new Color(128, 211, 128);
colormanager["flame"] = new Color(211, 34, 20);
// 克隆颜色
Color color1 = colormanager["red"].Clone() as Color;
Color color2 = colormanager["peace"].Clone() as Color;
Color color3 = colormanager["flame"].Clone() as Color;
Console.ReadKey();
}
|
3、实例运行结果
五、总结(Summary)
本文对原型模式(Prototype Pattern)的概念、设计结构图、代码、使用场景、深复制与浅复制的区别,以及如何Net平台下实现克隆进行了描述。以一个实例进行了说明。原型模式是比较常用和简单的设计模式。
本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/263881,如需转载请自行联系原作者