Design Patterns article

The mediator pattern

The proxy pattern

The bridge model

Abstract Factory Pattern details – Head First design pattern

Decorator pattern

Adapter mode

The strategy pattern

Observer model

Builder Mode

An overview of the

As the name suggests, the Chain of Responsibility Pattern creates a Chain of recipient objects for a request. This pattern decouples the sender and receiver of the request by giving the type of request. This type of design pattern is behavioral.

In this pattern, each receiver typically contains a reference to the other receiver. If an object cannot handle the request, it passes the same request to the next recipient, and so on.

In real life, there are often instances where a request can be processed by multiple objects, but each object has different processing conditions or permissions. Company staff leave, for example, can be batch of false leadership department, deputy general manager, general manager, director and so on, but each leader to approve the number of days, must according to their own staff leave the number of days to find different signatures of leadership, that is to say, employees must remember each leadership of the information such as name, phone number and address, this increases the difficulty. There are many such examples, such as looking for leaders to reimburse expenses on business trips, in the life of the “drum spread flowers” game.

There are also related examples in computer hardware and software, such as data transmission in the bus network, each computer according to whether the target address is the same as its own address to decide whether to receive; In exception handling, the handler decides whether or not to handle an exception based on its type; There are Struts2 interceptors, JSP and Servlet filters, and so on, all of which can be easily solved using the chain of responsibility model.

Definition and characteristics of patterns

The definition of Chain of Responsibility pattern: in order to avoid the request sender and multiple request handlers coupling together, all request handlers are linked into a Chain by the previous object remembering the reference of the next object; When a request occurs, it can be passed along the chain until an object processes it.

Note: The chain of responsibility model is also called the chain of responsibility model.

In the responsibility chain mode, the customer only needs to send the request to the responsibility chain, and does not need to care about the processing details of the request and the transmission process of the request, so the responsibility chain decouples the sender of the request from the handler of the request.

The chain of responsibility mode is an object behavior mode, and its main advantages are as follows.

  1. Reduces the degree of coupling between objects. This pattern makes it unnecessary for an object to know which object is handling its request and chain structure, and for sender and receiver to have explicit information about each other.
  2. The scalability of the system is enhanced. New request handling classes can be added as needed to satisfy the open close principle.
  3. Increased flexibility in assigning responsibilities to objects. As the workflow changes, members in the chain can be dynamically changed or reordered, and responsibilities can be dynamically added or removed.
  4. Chains of responsibility simplify the connection between objects. Each object maintains only one reference to its successors, not all other handlers, which avoids the need for numerous if or if· else statements.
  5. Burden sharing. Each class only needs to deal with its own work, should not deal with the next object to complete, clear the scope of responsibility, in line with the single responsibility of the class principle.

Its main disadvantages are as follows.

  1. There is no guarantee that every request will be processed. Because a request has no clear recipient, there is no guarantee that it will be processed, and the request may not be processed all the way to the end of the chain.
  2. For a long chain of responsibilities, the processing of the request may involve multiple processing objects, and the system performance will be affected to some extent.
  3. The rationality of responsibility chain establishment depends on the client to ensure, which increases the complexity of the client, and may lead to system errors due to the wrong setting of responsibility chain, such as circular invocation.

Structure and implementation of patterns

In general, you can implement the data structure of the responsibility chain pattern through a data link list.

1. Pattern structure

The responsibility chain pattern mainly consists of the following roles.

  1. The role of Abstract Handler: Defines an interface to process a request, including abstract processing methods and a subsequent connection.
  2. The role of Concrete Handler: Implements the processing method of the abstract Handler, determines whether the request can be processed, if it can be processed, and otherwise passes the request to its successor.
  3. The Client role: Creates a processing chain and submits a request to a specific handler object in the header. It does not care about processing details or the delivery of the request.

Its structure is shown in Figure 1. The client can set up the chain of responsibility as shown in Figure 2.



FIG. 1 Structure diagram of responsibility chain pattern

Figure 2 Chain of responsibility

2. Realization of patterns

The code of responsibility chain mode is as follows:

package chainOfResponsibility; Public class ChainOfResponsibilityPattern {public static void main (String [] args) {/ / assembly chain of responsibility Handler handler1 = new ConcreteHandler1(); Handler handler2=new ConcreteHandler2(); handler1.setNext(handler2); Handler1. HandleRequest ("two"); }} // class Handler {private Handler next; Public void setNext(Handler next) {this.next=next; } public Handler getNext() { return next; } public abstract void handleRequest(String request); } class ConcreteHandler1 extends Handler {public void handleRequest(String request) { If (request.equals("one")) {system.out.println (" Handler 1 is responsible for processing the request! ); } else { if(getNext()! =null) { getNext().handleRequest(request); } else {system.out.println (" No one is processing this request!" ); }}}} // ConcreteHandler2 extends Handler {public void handleRequest(String request) { If (request.equals("two")) {system.out.println (" Handler 2 is responsible for processing the request! ); } else { if(getNext()! =null) { getNext().handleRequest(request); } else {system.out.println (" No one is processing this request!" ); }}}}Copy the code

Application scenarios of the pattern

The structure and characteristics of the chain of responsibility mode have been described above, and its application scenarios are introduced below. The chain of responsibility mode is usually used in the following situations.

  1. Multiple objects can handle a request, and which object handles the request is automatically determined by the runtime.
  2. You can dynamically specify a set of objects to handle requests, or add new handlers.
  3. Submit a request to one of multiple handlers without explicitly specifying a request handler.

Schema extension

The chain of responsibility pattern has the following two situations.

  1. Pure chain of responsibility pattern: a request must be received by a handler object, and a handler can only handle a request in one of two ways: handle (assume responsibility); Pass the buck to the next boss.
  2. Impalent chain of responsibility pattern: it allows a specific handler to assume some responsibility for a request and then pass the rest to the next handler, and a request can end up not being received by any receiving object.