1. 程式人生 > 實用技巧 >設計模式 - 21)職責鏈模式

設計模式 - 21)職責鏈模式

graph LR client--呼叫-->Handler ConcreteHandlerA--繼承-->Handler ConcreteHandlerB--繼承-->Handler Handler--引用-->Handler

當 Handler 處理請求時,可以選擇自己處理或呼叫繼任者處理該請求。

abstract class Handler
{
    protected Handler _successor;

    public void SetSuccessor(Handler h)
    {
        this._successor = h;
    }

    public abstract void HandlerRequest(int request);
}

class ConcreteHandlerA : Handler
{
    public override void HandlerRequest(int request)
    {
        if (request < 10)
        {
            Console.WriteLine(string.Format("{0} handle thing which is {1}", this.GetType().Name, request));
        }
        else if (_successor != null)
        {
            Console.WriteLine(string.Format("{0} cannot handle thing which is {1}", this.GetType().Name, request));
            _successor.HandlerRequest(request);
        }
    }
}

class ConcreteHandlerB : Handler
{
    public override void HandlerRequest(int request)
    {
        if (request < 20)
        {
            Console.WriteLine(string.Format("{0} handle thing which is {1}", this.GetType().Name, request));
        }
        else if (_successor != null)
        {
            Console.WriteLine(string.Format("{0} cannot handle thing which is {1}", this.GetType().Name, request));
            _successor.HandlerRequest(request);
        }
    }
}

class ConcreteHandlerC : Handler
{
    public override void HandlerRequest(int request)
    {
        if (request < 30)
        {
            Console.WriteLine(string.Format("{0} handler thing which is {1}", this.GetType().Name, request));
        }
        else
        {
            Console.WriteLine(string.Format("{0} say {1} 太高了,再說吧", this.GetType().Name, request));
        }
    }
}

class Boy : Handler
{
    public override void HandlerRequest(int request)
    {
        _successor.HandlerRequest(request);
    }
}


// 業務程式碼:
ConcreteHandlerC c = new ConcreteHandlerC();
oncreteHandlerB b = new ConcreteHandlerB();
b.SetSuccessor(c);

ConcreteHandlerA a = new ConcreteHandlerA();
a.SetSuccessor(b);

int[] requests = {5, 15, 25, 35};
foreach (int res in requests)
{
    boy.HandlerRequest(res);
}
output:
ConcreteHandlerA handle thing which is 5

ConcreteHandlerA cannot handle thing which is 15
ConcreteHandlerB handle thing which is 15

ConcreteHandlerA cannot handle thing which is 25
ConcreteHandlerB cannot handle thing which is 25
ConcreteHandlerC handler thing which is 25

ConcreteHandlerA cannot handle thing which is 35
ConcreteHandlerB cannot handle thing which is 35
ConcreteHandlerC say 35 太高了,再說吧