原型模式(Prototype Pattern):用原型執行個體指定建立對象的種類,并通過拷貝這些原型建立新的對象。
Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype。
淺複制與深複制差別:
淺複制,被複制的所有變量都還有與原來對象相同的值,而所有的對其他對象的引用都仍然指向原來的對象。
深複制,把引用對象的變量指向複制過的新對象,而不是原有的被引用的對象。
Net命名空間System提供了一個IConeable接口,此接口隻有一個方法Clone(),隻需要實作這個接口就可以實作原型模式(Prototype Pattern)了。
當一個對象生成不是通過New而是通過複制舊對象的時候,可以考慮使用原型模式。

Prototype類:原型類 Clone()方法:克隆自身的接口。
ConcretePrototypeA、ConcretePrototypeA類:原型類的具體實作。克隆一個自身的操作。
1、原型抽象類Prototype
/// <summary>
/// 抽象原型模式類
/// </summary>
public abstract class Prototype
{
private string _id;
public Prototype(string id)
{
this.Id = id;
}
public string Id
get { return _id; }
set { _id = value; }
public abstract Prototype Clone();
}
2、具體實作類ConcretePrototypeA和ConcretePrototypeB
public class ConcretePrototypeA : Prototype
public ConcretePrototypeA(string id)
: base(id)
{ }
/// <summary>
/// Returns a shallow copy 淺拷貝
/// </summary>
/// <returns>a shallow copy</returns>
public override Prototype Clone()
return (Prototype)this.MemberwiseClone();
public class ConcretePrototypeB:Prototype
public ConcretePrototypeB(string id)
/// a shallow copy
/// <returns>淺拷貝</returns>
2、用戶端代碼
static void Main(string[] args)
Prototype pA = new ConcretePrototypeA("A");
Prototype cA = pA.Clone() as ConcretePrototypeA ;
Console.WriteLine("Cloned:"+cA.Id);
ConcretePrototypeB pB = new ConcretePrototypeB("B");
ConcretePrototypeB cB = (ConcretePrototypeB)pB.Clone();
Console.WriteLine("Cloned:"+cB.Id);
Console.ReadKey();
顔色索引器存儲多種顔色值,從顔色索引器中克隆客戶需要幾種顔色。結構如下圖所示
ColorManager類:顔色索引器
ColorPrototype類:原型模式抽象類
Color類:原型模式抽象類的具體實作,Clone方法的實作,克隆自身的操作
1、原型模式抽象類ColorPrototype及其具體實作類Color
/// 原型模式抽象類
public abstract class ColorPrototype
public abstract ColorPrototype Clone();
/// 具體實作類
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;
/// 實作淺複制
/// <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、用戶端代碼
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;
本文對原型模式(Prototype Pattern)的概念、設計結構圖、代碼、使用場景、深複制與淺複制的差別,以及如何Net平台下實作克隆進行了描述。以一個執行個體進行了說明。原型模式是比較常用和簡單的設計模式。
版權
作者:靈動生活 郝憲玮
如果你認為此文章有用,請點選底端的【推薦】讓其他人也了解此文章,
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。