原型模式(Prototype Pattern)屬於創建型模式,核心在於「用原型實例指定創建對象的種類,並通過拷貝這些原型創建新對象」。避免用 new 關鍵字實例化,而是透過克隆現有對象快速生成新實例,特別適合對象創建成本高或結構複雜的場景。
| 特性 | 淺拷貝 | 深拷貝 |
|---|---|---|
| 值類型字段 | 複製值 | 複製值 |
| 引用類型字段 | 複製引用(指向同一對象) | 遞歸複製引用對象(新對象) |
| .NET 實現 | MemberwiseClone() | 自定義邏輯 / 序列化反序列化 |
.NET 提供 ICloneable 介面,僅含 Clone() 方法。實現該介面即可賦予類別克隆能力,但需自行決定採用淺或深拷貝。

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();
}
public class ConcretePrototypeA : Prototype
{
public ConcretePrototypeA(string id) : base(id) { }
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone(); // 淺拷貝
}
}
public class ConcretePrototypeB : Prototype
{
public ConcretePrototypeB(string id) : base(id) { }
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone(); // 淺拷貝
}
}
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();
}
場景:系統預定義標準顏色(紅、綠、藍),用戶可克隆並微調生成個性化顏色(如「憤怒紅」、「寧靜綠」),避免重複創建顏色對象開銷。

public abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
public class Color : ColorPrototype
{
private int _red, _green, _blue;
public Color(int red, int green, int blue)
{
this._red = red; this._green = green; this._blue = blue;
}
public override ColorPrototype Clone()
{
Console.WriteLine("Cloning color RGB: {0,3},{1,3},{2,3}", _red, _green, _blue);
return this.MemberwiseClone() as ColorPrototype; // 淺拷貝(值類型足夠)
}
}
// 顏色管理器(原型註冊表)
public class ColorManager
{
private Dictionary _colors = new Dictionary();
public ColorPrototype this[string key]
{
get { return _colors[key]; }
set { _colors[key] = value; }
}
}
static void Main(string[] args)
{
ColorManager colormanager = new ColorManager();
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();
}
原型模式透過克隆機制簡化對象創建,配合 .NET ICloneable 與 MemberwiseClone() 易於落地。關鍵在於根據業務需求正確選擇淺/深拷貝策略。本文從原理到實戰完整演示,助您靈活應用於對象創建昂貴或結構相似的場景。