Java design pattern-responsibility chain model

Source: Internet
Author: User

The responsibility chain model, also known as the responsibility chain model, is classified as a behavioral pattern in 23 design patterns. Behavioral patterns can be categorized into class-behavioral patterns and object-behavioral patterns.

The class behavior pattern uses inheritance relationships to distribute behavior among several classes, and the class behavior pattern allocates the responsibilities of the parent class and the subclass primarily through polymorphism.

The object behavior pattern uses the aggregate association relation of the object to assign the behavior, and the object behavior pattern is to assign the responsibility of two or more classes by means of object recombination. According to the "synthetic reuse Principle", the system should try to use the combination relation to replace the inheritance relation, so most of the behavioral design patterns belong to the object-oriented design pattern. The model of responsibility chain is the model of object behavior.

In the chain of responsibility model, there are multiple objects that have the opportunity to process requests and avoid the request sender being coupled with the receiver. Connect these objects as a chain and pass the request along this chain until an object has processed it.

Typical responsibility chain model
The chain of responsibility typically involves two roles:

Abstract processor (Handler) role: Defines an interface for processing requests. If necessary, the interface can define a method to set and return a reference to the successor. This role is typically implemented by a Java abstract class or Java interface.
Specific processor (Concretehandler) role: When a specific processor receives a request, it can choose to either dispose of the request or pass the request to the successor. Because the specific processor holds a reference to the successor, the specific processor can access the successor if necessary.

Typical abstract Processor handler code
Public abstract class Handler {

private Handler successor;public Handler getSuccessor() {    return successor;}public void setSuccessor(Handler successor) {    this.successor = successor;}  public abstract void handleRequest();

}
Typical specific processor Concretehandler code
public class Concretehandler extends Handler {

@Overridepublic void handleRequest() {    if (请求满足条件) {        ...//处理请求    } else {        getSuccessor().handleRequest();//转发给后继者    }}

}
Example of a responsibility chain pattern
UI Control Event Delivery
The Helphandler class defines an interface for handling help requests. It holds the reference successor of the successor in the object chain, the key logic Handlehelp () method can be overridden by the quilt class, HasHelp () is a conditional judgment, mainly used to determine whether the current object is in accordance with the processing conditions, if satisfied will execute the Handlehelp () method.

public enum Topic {

NONE,BUTTON,DIALOG,APPLICATION

}

Public abstract class Helphandler {

private HelpHandler successor;private Topic topic;HelpHandler(HelpHandler successor, Topic topic) {    this.successor = successor;    this.topic = topic;}public void handleHelp() {    if (successor != null) {        successor.handleHelp();    }}public boolean hasHelp() {    return topic != Topic.NONE;}

}
All widgets are subclasses of widgets, and widgets are subclasses of Helphandler because all interface elements can have helpful topics.

Public abstract class Widget extends helphandler{

public Widget(HelpHandler successor, Topic topic) {    super(successor,topic);}

}
The button is the first event handler on the chain, because the button is also a window and component, so it is a subclass of the widget, and a widget is passed into the constructor, not a Helphandler class.

public class Button extends Widget {

public Button(Widget w, Topic topic) {    super(w, topic);}@Overridepublic void handleHelp() {    if (hasHelp()) {        System.out.println("Button handler");    } else {        super.handleHelp();    }}

}
Dialog a button-like implementation, except that its successor is not a widget component, but an arbitrary help request processing object, in this example its successor will be a application instance.

public class Dialog extends Widget {

public Dialog(HelpHandler successor, Topic topic) {    super(successor, topic);}@Overridepublic void handleHelp() {    if (hasHelp()) {        System.out.println("Dialog handler");    } else {        super.handleHelp();    }}

}
At the end of the chain is an application instance, and the application is not a window component. When a help request is passed to this layer, application can provide general information about the app, or it can provide a range of different help topics.

public class Application extends Helphandler {

Application(HelpHandler successor, Topic topic) {    super(successor, topic);}Application(Topic topic) {    this(null, topic);}@Overridepublic void handleHelp() {    if (hasHelp()) {        System.out.println("Application handler");    } else {        //具体逻辑操作    }}

}
The sample code is called as follows:

Application application = new application (topic.application);
Dialog Dialog = new Dialog (application, topic.dialog);
Button button = New button (dialog, Topic.button);
Button.handlehelp ();//button handler

Application application = new application (topic.application);
Dialog Dialog = new Dialog (application, topic.dialog);
Button button = New button (dialog, Topic.none);
Button.handlehelp ();//dialog handler
The example is handled in a similar way to UI user events, and event handling in Android is also used for the responsibility chain pattern. Now the more popular network request library Okhttp, its internal in the processing network request is the use of the responsibility chain model, in the development of Java EE Filter is also the chain of responsibility model, you can see that at some framework level, the responsibility chain model used quite extensive.

Copy-write servlet filter
Has a string msg = ":):, <script>, sensitive, employed, web-taught"; we want to apply the following three rules to filter the strings harmoniously:

Replace the "<>" symbol that appears in the string with "[]";
Handling sensitive information in strings, will be employed in harmony into employment;
Convert ":):" appearing in the string to "^v^";
First look at the defined request and response as well as the filter interface.

public class Request {

public String request;

}
public class Response {

public String response;

}
Public interface Filter {

// 定义接口Filter,具体的过滤规则需要实现这个接口void doFilter(Request request, Response response, FilterChain chain);

}
Filterchain is defined as follows:

public class Filterchain implements Filter {

// 用List集合来存储过滤规则List<Filter> filters = new ArrayList<Filter>();// 用于标记规则的引用顺序int index = 0;// 往规则链条中添加规则public FilterChain addFilter(Filter f) {    filters.add(f);    // 代码的设计技巧:Chain链添加过滤规则结束后返回添加后的Chain,方便我们下面doFilter函数的操作    return this;}@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {    // index初始化为0,filters.size()为3,不会执行return操作    if (index == filters.size()) {        return;    }    // 每添加一个过滤规则,index自增1    Filter f = filters.get(index);    index++;    // 根据索引值获取对应的规律规则对字符串进行处理    f.doFilter(request, response, chain);}

}
Defines the filtering processing logic.

public class Htmlfilter implements Filter {

@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {    request.request = request.request.replace(‘<‘, ‘[‘).replace(‘>‘, ‘]‘) +    // 后面添加的是便于我们观察代码执行步骤的字符串            "----HTMLFilter()";    chain.doFilter(request, response, chain);    response.response += "---HTMLFilter()";}

}
public class Facefilter implements Filter {

@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {    // 将字符串中出现的":):"转换成"^V^";    request.request = request.request.replace(":):", "^V^")    // 后面添加的是便于我们观察代码执行步骤的字符串            + "----FaceFilter()";    chain.doFilter(request, response, chain);    response.response += "---FaceFilter()";}

}
public class Sensitivefilter implements Filter {

@Overridepublic void doFilter(Request request, Response response, FilterChain chain) {    // 处理字符串中的敏感信息,将被就业和谐成就业    request.request = request.request.replace("被就业", "就业")            .replace("敏感", "") +    // 后面添加的是便于我们观察代码执行步骤的字符串            " ---sensitiveFilter()";    chain.doFilter(request, response, chain);    response.response += "---sensitiveFilter()";}

}
The sample test code is as follows:

String msg = ":):, <script>, sensitive, employed, web-taught";
Request Request = new request ();
Request.request = msg;
Response Response = new Response ();
Response.response = "Response:";
Filterchain, the blocking chain formed by the filter rules
Filterchain FC = new Filterchain ();
The rule chain adds a filter rule that uses a chain call
Fc.addfilter (New Htmlfilter ())
. addfilter (New Sensitivefilter ())
. addfilter (New Facefilter ());
Apply filter rules in order of Filterchain rules
Fc.dofilter (Request, response, FC);
Print request Information
System.out.println (request.request);
Print response information
System.out.println (Response.response);
The sample output is as follows:

^v^,[script],, employment, online teaching----htmlfilter ()---sensitivefilter ()----facefilter ()
Response:---facefilter ()---sensitivefilter ()---htmlfilter ()
Summary
The main advantage of the responsibility chain model is that it can reduce the coupling degree of the system, simplify the mutual connection of objects, and enhance the flexibility of assigning responsibilities to the object, and it is convenient to add new request processing classes, the main disadvantage is that the request must be received, and for the long chain of responsibility, the processing of the request may involve multiple processing objects. System performance is affected and is not convenient for code debugging.

The chain of responsibility can be divided into pure and impure chains of responsibility. A pure responsibility chain pattern requires a specific processor object to select only one of two behaviors: one is to take responsibility, the other is to put the blame on the next person. A situation in which a specific processor object is not allowed to transmit responsibility after taking part of the responsibility. In a pure chain of responsibility, a request must be received by a handler object, and in an impure chain of responsibility, a request can eventually not be received by any of the receiving end objects.

Java design pattern-responsibility chain model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.