Design mode ~ behavioral mode ~ responsibility chain mode ~ chain of responsibility pattern.

lyfGeek 2022-05-22 11:58:07 阅读数:174

designmodebehavioralmoderesponsibility

Design patterns ~ Behavioral patterns ~ The chain of responsibility model ~ Chain of Responsibility Pattern.



what.

in real life , There are often such cases : A request has more than one object to handle , But the processing conditions or permissions of each object are different .

eg. Employees ask for leave , The leader who can approve the fake has the head of the Department 、 Deputy general manager 、 General manager, etc , But the number of days each leader can approve is different , Employees must find different leaders to sign according to the number of days they want to leave , In other words, employees must remember the name of each leader 、 Phone and address information , This increases the difficulty . There are many other examples , For example, ask leaders for business trip reimbursement 、 In life “ Beat the drum to spread the flowers ” Games etc. .

Also known as responsibility chain model , In order to avoid coupling the request sender with multiple request processors , Link all request processors into a chain by remembering the reference of the next object by the previous object ; When a request occurs , The request can be passed along this chain , Until an object processes it .


structure .

The responsibility chain model mainly includes the following roles .

  • Abstract processor (Handler) role .
    Define an interface to process requests , Contains abstract processing methods and a subsequent connection .

  • Specific handler (Concrete Handler) role .
    Implement the processing methods of the abstract processor , Determine whether the request can be processed , If the request can be processed, process , Otherwise, forward the request to its successor .

  • Customer class (Client) role .

  • Create a processing chain , And submit the request to the specific handler object of the chain head , It doesn't care about processing details and the delivery of requests .


eg..

Now we need to develop a leave process control system . If you ask for less than one day off, you only need the consent of the team leader ; Ask for leave 1 Day to 3 The day off also needs the approval of the Department Manager ; request 3 Day to 7 I still need the approval of the general manager .

 Insert picture description here







advantage .

  • It reduces the coupling between objects .
    This mode reduces the coupling between the sender and receiver of the request .

  • Enhanced system scalability .
    You can add new request processing classes as needed , It satisfies the open close principle .

  • Increased flexibility in assigning responsibilities to objects .
    When the workflow changes , You can dynamically change the members in the chain or modify their order , You can also dynamically add or delete responsibilities .

  • The chain of responsibility simplifies the connection between objects .
    An object only needs to maintain a reference to its successor , No need to keep references from all other processors , This avoids using a lot of if perhaps if···else sentence .

  • Share responsibility .
    Each class only needs to handle its own work , What cannot be processed is passed to the next object to complete , Clarify the scope of responsibility of all kinds , According to the single responsibility principle of class .


shortcoming .

  • There is no guarantee that every request will be processed . Because a request has no clear recipient , So there's no guarantee that it will be dealt with , The request may not be processed all the way to the end of the chain .

  • For a longer responsibility chain , The processing of the request may involve multiple processing objects , System performance will be affected .

  • The rationality of responsibility chain establishment depends on the client to ensure , Increased client complexity , System error may be caused by wrong setting of responsibility chain , If it is possible to cause a circular call .


The source code parsing .

stay JavaWeb Application development ,FilterChain It's the responsibility chain ( filter ) Typical application of pattern , Here are Filter Analysis of the simulation implementation of .

  • simulation web request Request as well as web Respond to Response.
public interface Request{

}
public interface Response{

}
  • simulation web filter Filter.
public interface Filter {

public void doFilter(Request req,Response res,FilterChain c);
}
  • Simulate the implementation of specific filters .
public class FirstFilter implements Filter {

@Override
public void doFilter(Request request, Response response,
FilterChain chain) {

System.out.println(" filter 1 Preprocessing ");
// Do everything first request Then execute all... In reverse order response
chain.doFilter(request, response);
System.out.println(" filter 1 Post processing ");
}
}
public class SecondFilter implements Filter {

@Override
public void doFilter(Request request, Response response,
FilterChain chain) {

System.out.println(" filter 2 Preprocessing ");
// Do everything first request Then execute all... In reverse order response
chain.doFilter(request, response);
System.out.println(" filter 2 Post processing ");
}
}
  • Simulate the implementation of filter chain FilterChain.
public class FilterChain {

private List<Filter> filters = new ArrayList<Filter>();
private int index = 0;
// call chaining 
public FilterChain addFilter(Filter filter) {

this.filters.add(filter);
return this;
}
public void doFilter(Request request, Response response) {

if (index == filters.size()) {

return;
}
Filter filter = filters.get(index);
index++;
filter.doFilter(request, response, this);
}
}
public class Client {

public static void main(String[] args) {

Request req = null;
Response res = null ;
FilterChain filterChain = new FilterChain();
filterChain.addFilter(new FirstFilter()).addFilter(new
SecondFilter());
filterChain.doFilter(req,res);
}
}
copyright:author[lyfGeek],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202203140552360290.html