[設計模式練習]原型模式

[設計模式練習]原型模式

食物菜單 : 一個客人可以點不同的菜並指定不同服務生

類別圖

ProtoType

物件檔定義

using System.Collections.Generic;
using System.Text;

namespace DesignModelTest.原型
{
    /// <summary>
    /// 食物菜單:一個客人可以點不同的菜並指定不同服務生
    /// </summary>
    class FoodMenu : ICloneable
    {
        private string _customername;
        private string _orderfood;
        Waiter waiter;
        public FoodMenu(string name)
        {
            this._customername = name;
            this.waiter = new Waiter();
        }
        //深複製
        private FoodMenu(Waiter wa)
        {
            this.waiter = (Waiter)wa.Clone();
        }
        public void SetFood(string orderfood)
        {
            this._orderfood = orderfood;
        }
        public void SetWaiter(string name)
        {
            this.waiter.waitername = name;
        }
        public void ShowMenu()
        {
            Console.WriteLine(this._customername+"\t點選\t"+this._orderfood+"\t服務生\t"+waiter.waitername);
        }
        //深複製的clone實作
        public object Clone()
        {
            FoodMenu fm = new FoodMenu(this.waiter);
            fm._customername = this._customername;
            fm._orderfood = this._orderfood;
            return fm;
        }
    }
    /// <summary>
    /// 服務生
    /// </summary>
    class Waiter : ICloneable
    {
        private string _waitername;
        public string waitername
        {
            get { return _waitername; }
            set { _waitername = value; }
        }
        //淺複製的clone實作
        public object Clone()
        {
            return (object)this.MemberwiseClone();
        }
    }
    
}

用戶端程式碼

            DesignModelTest.原型.FoodMenu f1 = new DesignModelTest.原型.FoodMenu("大雕哥");
            //複製物件
            DesignModelTest.原型.FoodMenu f2 = (DesignModelTest.原型.FoodMenu)f1.Clone();
            //設定相關參數及調用方法
            f1.SetFood("食物一");
            f1.SetWaiter("服務生一");
            f2.SetFood("食物二");
            f2.SetWaiter("服務生二");
            f1.ShowMenu();
            f2.ShowMenu();
            Console.Read();
            #endregion

輸出結果

pic2