using System;
abstract class Prototype
{
private string id;
protected Prototype(string id) => this.id = id;
public string Id => id;
public abstract Prototype Clone();
}
class ConcretePrototype1 : Prototype
{
public ConcretePrototype1(string id) : base(id) { }
public override Prototype Clone() => (Prototype)MemberwiseClone();
}
class ConcretePrototype2 : Prototype
{
public ConcretePrototype2(string id) : base(id) { }
public override Prototype Clone() => (Prototype)MemberwiseClone();
}
class Client
{
static void Main()
{
ConcretePrototype1 p1 = new ConcretePrototype1("I");
ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
Console.WriteLine("Cloned: " + c1.Id);
ConcretePrototype2 p2 = new ConcretePrototype2("II");
ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
Console.WriteLine("Cloned: " + c2.Id);
}
}
Prototype 為抽象基類,定義 Id 與抽象 Clone()。MemberwiseClone() 實作淺拷貝。MemberwiseClone() 為 Object protected 方法,複製值型別欄位、參考型別複製參考位址。若需深拷貝,請實作 ICloneable 介面並自行在 Clone() 中逐欄位複製參考型別欄位 (如陣列、物件)。