Friday, June 7, 2013

Chain of Responsibility Design Patterns (Behavioral Patterns) in C#

The classes and/or objects participating in this pattern are:
        Handler   (Approver)
      ***defines an interface for handling the requests
        (optional) implements the successor link
        **ConcreteHandler   (Director, VicePresident, President) handles requests it is responsible for can access its successor
        if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor
        **Client   (ChainApp) initiates the request to a ConcreteHandler object on the chain

class Program
    {
        static void Main(string[] args)
        {
            Handler h1 = new ConcreteHandler();
            Handler h2 = new ConcreteHandler2();
            Handler h3 = new ConcreteHandler3();

            h1.SetSuccessor(h2);
            h2.SetSuccessor(h3);

            //Generate the process request
            int[] requests = { 1, 18, 25, 4, 5 };
            foreach (int request in requests)
            {
                h1.HandleRequest(request);
            }

            Console.ReadKey();
        }
    }

    abstract class Handler
    {
        protected Handler successor;
        public void SetSuccessor(Handler successor)
        {
            this.successor = successor;
        }
        public abstract void HandleRequest(int? request);
    }
    //ConcreteHandler
    class ConcreteHandler : Handler
    {
        public override void HandleRequest(int? request)
        {
            if (request >= 0 && request < 10)
                Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
            else if (request != null)
            {
                successor.HandleRequest(request);
            }
        }
    }
    //ConcreteHandler2
    class ConcreteHandler2 : Handler
    {
        public override void HandleRequest(int? request)
        {
            if (request >= 10 && request < 20)
                Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
            else if (request != null)
            {
                successor.HandleRequest(request);
            }
        }
    }
    //ConcreteHandler3
    class ConcreteHandler3 : Handler
    {
        public override void HandleRequest(int? request)
        {
            if (request >= 20 && request < 30)
                Console.WriteLine("{0} handled request {1}", this.GetType().Name, request);
            else if (request != null)
            {
                successor.HandleRequest(request);
            }
        }
    }

No comments:

Post a Comment