[設計模式練習]裝飾模式

[設計模式練習]裝飾模式

將行為分成吃喝睡用裝飾模式設計

一個人行為可以進行多種 , 但不一定要同時執行

類別圖

Decorator

 

物件檔定義


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

namespace DesignModelTest.裝飾
{
    /// <summary>
    /// 元件
    /// </summary>
    abstract class Behavior
    {
        public abstract void Operation();
    }
    /// <summary>
    /// 具體物件的操作
    /// </summary>
    class PeopleAction : Behavior
    {
        private string _name;
        public PeopleAction(string name)
        {
            this._name = name;
        }
        public override void Operation()
        {
            Console.Write("{0}的行為:", _name);
        }
    }
    /// <summary>
    /// 裝飾
    /// </summary>
    abstract class Decorator : Behavior
    {
        protected Behavior behavior;
        public void SetBehavior(Behavior be)
        {
            this.behavior = be;
        }
        public override void Operation()
        {
            if (behavior != null)
                behavior.Operation();
        }
    }
    /// <summary>
    /// 裝飾物件:吃
    /// </summary>
    class Eat : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            Console.Write("\t吃");
        } 
    }
    /// <summary>
    /// 裝飾物件:喝
    /// </summary>
    class Drink : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            Console.Write("\t喝");
        }
    }
    /// <summary>
    /// 裝飾物件:睡
    /// </summary>
    class Sleep : Decorator
    {
        public override void Operation()
        {
            base.Operation();
            Console.Write("\t睡");
        }
    }
}

用戶端程式碼


            DesignModelTest.裝飾.PeopleAction paction = new PeopleAction("王大明");
            DesignModelTest.裝飾.Drink drink = new Drink();
            DesignModelTest.裝飾.Eat eat = new Eat();
            DesignModelTest.裝飾.Sleep sleep = new Sleep();
            //將裝飾一一掛上去
            drink.SetBehavior(paction);
            eat.SetBehavior(drink);
            sleep.SetBehavior(eat);
            //吃喝睡
            sleep.Operation();
            Console.Write(Environment.NewLine);
            //吃喝
            eat.Operation();
            Console.Read();
            #endregion

輸出結果

pic3