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

C# 設計模式:原型模式 (3) - 原型管理器模式完整實作 (ColorManager 範例)

     編輯:關於C語言

帶 Prototype Manager 結構 (UML)

  • Client:向管理器請求建立物件。
  • Prototype (抽象原型):定義 Clone(),通常實作 ICloneable。
  • Concrete Prototype:被複製物件 (如 Color)。
  • Prototype Manager:建立、儲存、管理原型實例 (如 ColorManager)。

完整程式碼範例

using System;
using System.Collections;

abstract class ColorPrototype { public abstract ColorPrototype Clone(); }

class Color : ColorPrototype
{
    private int red, green, blue;
    public Color(int r, int g, int b) { red=r; green=g; blue=b; }
    public override ColorPrototype Clone() => (ColorPrototype)MemberwiseClone(); // 淺拷貝 (值型別足夠)
    public void Display() => Console.WriteLine($"RGB: {red},{green},{blue}");
}

class ColorManager
{
    Hashtable colors = new Hashtable();
    public ColorPrototype this[string name]
    {
        get => (ColorPrototype)colors[name];
        set => colors.Add(name, value);
    }
}

class PrototypeApp
{
    static void Main()
    {
        ColorManager cm = new ColorManager();
        // 標準色
        cm["red"]   = new Color(255, 0, 0);
        cm["green"] = new Color(0, 255, 0);
        cm["blue"]  = new Color(0, 0, 255);
        // 使用者自訂色
        cm["angry"] = new Color(255, 54, 0);
        cm["peace"] = new Color(128, 211, 128);
        cm["flame"] = new Color(211, 34, 20);

        // 客戶端使用
        Color c1 = (Color)cm["red"].Clone();   c1.Display();
        Color c2 = (Color)cm["peace"].Clone(); c2.Display();
        Color c3 = (Color)cm["flame"].Clone(); c3.Display();
    }
}

關鍵點

  • ColorManager 以 Hashtable 索引器管理原型,支援標準色與使用者自訂色混存。
  • Color 為純值型別欄位,MemberwiseClone() 即為深拷貝。
  • 客戶端無需知道具體建構細節,僅透過名稱索引並 Clone() 取得新實例。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved