首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 設計模式:原型模式 (2) - 結構性程式碼與淺拷貝實作

     編輯:關於C語言

結構性程式碼範例

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() 中逐欄位複製參考型別欄位 (如陣列、物件)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved