Chain of Responsibility pattern design pattern (Chain of Responsibility) and Code Example Explanation

First, the definition and characteristics of the chain of responsibility pattern

  Defined chain of responsibility (Chain of Responsibility) mode: Chain of Responsibility pattern is also called duty chain, in order to avoid a plurality of request sender and the request handler are coupled together, the process by which all requests to remember next by the preceding objects the referenced object and connected into a chain; occurs when there is a request, the request can be transmitted along the chain until an object handles it so far.

  In the chain of responsibility pattern, the customer simply send the request to the chain of responsibility to process the request and details of the transfer process without concern for the request, so the sender and handler request chain of responsibility will request decoupled.

Second, the advantages and disadvantages of chain of responsibility pattern

  Chain of Responsibility pattern is an object behavioral pattern, and its main advantages are as follows:

  • Reducing the coupling between objects. This mode allows an object need not know which in the end is a structure which is the object request and the processing chain, the sender and recipient need not have each other also clear message.
  • Enhancing the scalability of the system. You can add a new category of request processing as required to satisfy the principle of opening and closing.
  • Enhancing the flexibility of assigning responsibilities to objects. When the workflow changes, you can dynamically change the members in the chain or mobilize their order can also be dynamically added or deleted responsibility.
  • Chain of Responsibility simplifies the connection between the objects. Each object just keep a reference to its successor, without reference to keep all other handlers, which avoids the use of a large number of if statements or if ··· else.
  • Shared responsibility. Each class need only deal with the process of their work, should not be passed to the next object processing is complete, clear all kinds of areas of responsibility, in line with the principle of single responsibility class.

  The main disadvantages are as follows:

  • We can not guarantee that each request must be processed. As the recipient of a request is not clear, we can not guarantee that it will be processed, the request may have been passed to the end of the chain are not processed.
  • Comparative longer duty chain, processing the request may involve a plurality of processing objects, the system performance will be affected.
  • Customers rely on the rationality of the established chain of responsibility to ensure the end, increase the complexity of the client, may be due to incorrect settings duty chain and cause system errors, such as may result in the cycle call.

Third, to achieve chain of responsibility pattern

  Typically, the data structure may be realized by the duty chain linked list data.

  Duty chain mainly includes the following roles.

  • Abstract handler (Handler) Roles: defining a processing request to an interface, and a processing method comprising abstract subsequent connection.
  • DETAILED handler (Concrete Handler) Cast: abstract handlers implement the processing methods, the process determines whether this request, if the request can be processed, otherwise it forwards the request to the successor.
  • Customer class (Client) role: to create processing chain, and target specific handler chain first submit a request, it does not care about the details of the transfer process and handle the request.

  The structure shown in Figure:

          

  The client may be arranged as shown in FIG Chain of Responsibility:

            

   Code is implemented as follows:

public  class ChainOfResponsibilityPattern 
{ 
    public  static  void main (String [] args) 
    { 
        // assembled chain of responsibility 
        Handler handler1 = new new ConcreteHandler1 (); 
        Handler handler2 is = new new ConcreteHandler2 (); 
        handler1.setNext (handler2 is); 
        // submit a request 
        handler1.handleRequest ( "TWO" ); 
    } 
} 
// abstraction character 
abstract  class Handler 
{ 
    Private Handler Next;
     public  void SetNext (Next Handler) 
    {
        the this .next = Next; 
    } 
    public Handler getNext () 
    { 
        return Next; 
    }    
    // method of processing a request 
    public  abstract  void the handleRequest (Request String);        
} 
// specific processing role. 1 
class ConcreteHandler1 the extends Handler 
{ 
    public  void the handleRequest (String request) 
    { 
        IF (request.equals ( "One" )) 
        { 
            System.out.println ( "1 are specifically responsible for processing the request!" );        
        } 
        the else 
        {
            IF (getNext () =! null ) 
            { 
                getNext () the handleRequest (Request);.              
            } 
            the else 
            { 
                System.out.println ( "no process the request!" ); 
            } 
        } 
    } 
} 
// specific processing role 2 
class ConcreteHandler2 the extends Handler 
{ 
    public  void the handleRequest (request String) 
    { 
        IF (request.equals ( "TWO" )) 
        { 
            System.out.println ( "2 are specifically responsible for processing the request!"  );       
        }
         The else 
        { 
            IF (! GetNext () = null ) 
            { 
                getNext () the handleRequest (Request);.              
            } 
            The else 
            { 
                System.out.println ( "no process the request!" ); 
            } 
        } 
    } 
}

  Results are as follows:

2 specific handler is responsible for processing the request!

Fourth, application examples chain of responsibility pattern

  Chain of Responsibility pattern design with a written request for approval module: if equal to or less than a predetermined students leave two days, the teacher may approve; less than or equal to 7 days, Dean approve; less than or equal to 10 days, Dean may approve; without other I approve.

  First, define a leader class (Leader), which is an abstract handler, it contains a pointer to the next leader pointer next and abstract processing method handleRequest (int LeaveDays) a process dummy bar; then, define the class category (ClassAdviser), Head of the class (DepartmentHead) and Dean class (Dean), which is a subclass of the abstract handler, the handler is specific, it is necessary to realize the parent class handleRequest (int LeaveDays) method based on their own power, if not entitled to deal with it the application for leave to the next specific handler until the last; customer class is responsible for creating the processing chain, and specific handler chain for leave to head (teacher). Code as follows:

public  class LeaveApprovalTest 
{ 
    public  static  void main (String [] args) 
    { 
        // assembled chain of responsibility 
        Leader leader1 = new new ClassAdviser (); 
        Leader leader2 = new new DepartmentHead (); 
        Leader leader3 = new new Dean (); 
        leader1.setNext (leader2) ; 
        leader2.setNext (leader3); 
        // submit a request 
        leader1.handleRequest (. 8 ); 
    } 
} 
// abstraction by: leader class 
abstract  class leader 
{ 
    PrivateNext Leader;
     public  void SetNext (Next Leader) 
    { 
        the this .next = Next; 
    } 
    public Leader getNext () 
    { 
        return Next; 
    }    
    // method of processing a request 
    public  abstract  void the handleRequest ( int LeaveDays);        
} 
// specific handler 1 : class class 
class ClassAdviser the extends Leader 
{ 
    public  void the handleRequest ( int LeaveDays) 
    { 
        IF (LeaveDays <= 2 ) 
        {
            System.out.println ( "teacher approve your leave" + LeaveDays + "days." );        
        } 
        The else 
        { 
            IF (! GetNext () = null ) 
            { 
                getNext () handleRequest (LeaveDays);.              
            } 
            The else 
            { 
                  System.out. println ( "leave a few too many days without approval of the application for leave!" ); 
            } 
        } 
    } 
} 
// specific treatment in 2: Head of the class 
class DepartmentHead the extends Leader 
{ 
    public  void handleRequest ( int LeaveDays)
    { 
        IF (LeaveDays <=. 7 ) 
        { 
            System.out.println ( "You leave the Dean" + LeaveDays + "days." );        
        } 
        The else 
        { 
            IF (! GetNext () = null ) 
            { 
                  getNext () the handleRequest (. LeaveDays);              
            } 
            the else 
            { 
                System.out.println ( "too many leave days without approval of the application for leave!" ); 
           } 
        } 
    } 
} 
// specific treatment in 3: Dean class 
class Dean the extends Leader 
{ 
    public void the handleRequest ( int LeaveDays) 
    { 
        IF (LeaveDays <= 10 ) 
        { 
            System.out.println ( "leave your approval of the president" + LeaveDays + "days." );        
        } 
        the else 
        { 
              IF (getNext () =! null ) 
            { 
                getNext () handleRequest (LeaveDays);.              
            } 
            the else 
            { 
                  System.out.println ( "too many leave days without approval of the application for leave!" ); 
            } 
        } 
    } 
}

  Operating results as follows:

Dean approve your leave eight days.

  If you now add a Provost class, students may grant leave for 20 days, it is also very simple, as follows:

// specific processing by 4: Provost class 
class DeanOfStudies the extends Leader 
{ 
    public  void the handleRequest ( int LeaveDays) 
    { 
        IF (LeaveDays <= 20 is ) 
        { 
            System.out.println ( "leave your approval Provost" + LeaveDays + "Day . " );        
        } 
        the else 
        { 
              IF (getNext () =! null ) 
            { 
                getNext () handleRequest (LeaveDays);.           
            } 
            the else 
            { 
                  System.out.println ( " too many leave days without approval of the application for leave "! );
            }
        } 
    } 
}

  Then add in the chain of responsibility directly on the assembly to the Provost:

Leader leader4=new DeanOfStudies();
leader3.setNext(leader4);

Fifth, the chain of responsibility pattern scenarios

  Front have been told about the structure and characteristics of the chain of responsibility pattern, the following describes the application scenario, the chain of responsibility pattern is commonly used in the following situations.

  • A plurality of object can process the request, which object is automatically determined by the request processing runtime.
  • Dynamically processing request specifies a set of objects, or add new processor.
  • Without explicitly request handlers, submit requests to a plurality of handlers.

Extended Six, chain of responsibility pattern

  The following two cases duty chain.

  • Pure chain of responsibility pattern: a request must be received by one handler object and a specific handler to process a request can only take one of two actions: their own treatment (responsibility); passing the buck to treatment under the house.
  • Impure duty chain: allowed on a specific object handler to assume responsibility for a part of the case where the request is then passed to the next home responsibilities remaining, and a final request can not be received by any receiver-side object.

Guess you like

Origin www.cnblogs.com/jing99/p/12610095.html