责任链模式(Chain of Responsibility)

在 面向对象程式设计里, 责任链模式是一种软件设计模式,它包含了一些命令对象和一系列的处理对象。每一个处理对象决定它能处理哪些命令对象,它也知道如何将它不能处理的命令对象传递给该链中的下一个处理对象。该模式还描述了往该处理链的末尾添加新的处理对象的方法。

举例:总裁,副总,经理,都可以批准请假,经理批准有权批准1,副总2,总裁3,他们做不了主,就一层一层上报,

using System;

namespace DoFactory.GangOfFour.Chain.RealWorld
{
   
    class MainApp
    {
        static void Main()
        {
           
            Leave larry = new Director();
            Leave sam = new VicePresident();
            Leave tammy = new President();

            larry.SetSuccessor(sam);
            sam.SetSuccessor(tammy);

       
            Note p = new Note(3);
            larry.ProcessRequest(p);


          
            Console.ReadKey();
        }
    }

 
    abstract class Leave
    {
        protected Leave successor;

        public void SetSuccessor(Leave successor)
        {
            this.successor = successor;
        }

        public abstract void ProcessRequest(Note Note);
    }

    class Director : Leave
    {
        public override void ProcessRequest(Note Note)
        {
            if (Note.Day <=3)
            {
                Console.WriteLine("以批 3");
            }
            else if (successor != null)
            {
                successor.ProcessRequest(Note);
            }
        }
    }

    /// <summary>
    /// The 'ConcreteHandler' class
    /// </summary>
    class VicePresident : Leave
    {
        public override void ProcessRequest(Note Note)
        {
            if (Note.Day <= 2)
            {
                Console.WriteLine("以批 2");
            }
            else if (successor != null)
            {
                successor.ProcessRequest(Note);
            }
        }
    }

    class President : Leave
    {
        public override void ProcessRequest(Note purchase)
        {
            if (purchase.Day <= 1)
            {
                Console.WriteLine("以批 1");
            }
            else
            {
                Console.WriteLine("我只批一天的,半天别找我....");
            }
        }
    }

   
    class Note
    {
        private int _day;
       
     
        public Note(int day)
        {
            this._day = day;
        }
           

     
        public int Day
        {
            get { return _day; }
            set { _day = value; }
        }

       
    }
}

 

posted @ 2014-07-11 06:01  欢呼雀跃  阅读(193)  评论(0)    收藏  举报