My Java design pattern-the responsibility chain model

Source: Internet
Author: User

Today, the programmer's little ape and the product is about the need to happen the story. Not long ago, the little ape received the demand for the product.

Product Manager: Little Ape, in order to cater to the public cock Silk User's taste, we want to put a picture, to dew point.

Little Ape: ... Dew point? Your uncle's, let as a righteous and pure incarnate I do this demand, also dew point.

Product Manager: Misunderstanding misunderstanding, is to put a piece of exposed a little, small size.

Little ape: Can you say it clearly, the demand is ambiguous. No, I'm going to report the boss.

Product Manager also a burst of silent, this bean ding thing also reported boss. The report also has to go through the procedure is, the technical manager will not do, "with what to skip me, you have to pass me to the boss." Ah ~ This layer of the report is related to the responsibility chain model .

Definition of responsibility Chain model

?? Create multiple objects so that the objects form a chain and pass the request along this chain until an object on the chain decides to process the request.

Characteristics

1) The object that receives the request is connected to a chain , and there is a hierarchical relationship between the objects.

2) These objects can process the request, or it can pass the request until an object has processed the request.

Uml

The roles involved in the responsibility chain model are as follows:

?? -Abstract Processor role: Defines the interface or abstract class that handles requests, provides methods for handling requests, and sets the method for the next processor.

?? -specific processor role: Implement or inherit abstract this role, the specific logic according to the actual architecture to be determined, will be mentioned later.

Second, actual combat

First look at the abstract processor role code:

public abstract class Handler {    private Handler nextHandler;    private int level;    public Handler(int level) {        this.level = level;    }    // 处理请求传递,注意final,子类不可重写    public final void handleMessage(Demand demand) {        if (level == demand.demandLevel()) {            this.report(demand);        } else {            if (this.nextHandler != null) {                System.out.println("事情太严重,需报告上一级");                this.nextHandler.handleMessage(demand);            } else {                System.out.println("我就是boss,没有上头");            }        }    }    public void setNextHandler(Handler handler) {        this.nextHandler = handler;    }    // 抽象方法,子类实现    public abstract void report(Demand demand);}

In the abstract processor role, which defines the abstract method for processing requests, and the next level of object methods, focusing on how the Handlemessage handles the request delivery, the following explains why it is written and continues to look down.

Here are the specific processor roles that inherit the abstract processor role, and in our scenario there are two specific handlers, namely the technical manager and boss.

// 技术经理public class TechnicalManager extends Handler {    public TechnicalManager() {        super(1);    }    @Override    public void report(Demand demand) {        System.out.println("需求:" + demand.detail());        System.out.println(getClass().getSimpleName() + ":小猿我挺你,这个需求不干");    }}// bosspublic class Boss extends Handler {    public Boss() {        super(2);    }    @Override    public void report(Demand demand) {        System.out.println("需求:" + demand.detail());        System.out.println(getClass().getSimpleName() + ":你们打一架吧,打赢的做决定");    }}

You can see that the code for the specific processor is concise, overriding the report method and implementing the respective business logic, thanks to the Handlemessage method in the parent class.

All two roles are defined to see how the client implements:

public class Client {    public static void main(String[] args) {        Demand demandA = new DemandA(); // 请求等级低        Demand demandB = new DemandB(); // 请求等级高        Boss boss = new Boss();        TechnicalManager technicalManager = new TechnicalManager();        technicalManager.setNextHandler(boss); // 设置下一级        technicalManager.handleMessage(demandA);        System.out.println("============================");        technicalManager.handleMessage(demandB);    }}

You can see that the focus in the client is to set the next-level processor so that multiple processor objects form a chain. Run the client with the following results:

Need: Add a little bit of picture

Technicalmanager: Little Ape I'm with you, this demand is not dry

============================

Need: Add a little bit of picture

Technicalmanager: Things are too serious to be reported on the previous level

Boss: You fight, you win the decision

From the results can be seen, low-level request technical Manager to handle their own, high-level delivery to the next level of the boss, so that the formation of a chain , and this is the core of the chain of responsibility. Note that the request is not changed during the delivery of the request. Demand does not change from "Add a little bit of a picture" to "add a picture of dew point", wait for boss please go to the office to drink tea.

Iii. expansion of the chain of responsibility + template approach

Looking back at the code above, there are several methods defined in the abstract class, one is the final modified Handlemessage, one is the abstract method report, and the other is the Setnexthandler. This is exactly three basic methods in the template method pattern, namely the concrete method (abstract class declaration and implementation, subclass not implemented), abstract method (abstract class declaration, subclass must be implemented), hook method (abstract class declaration and implementation, subclass extensible). The Handlemessage method adds the final modifier, the subclass cannot be overridden, and Handlemessage is handing over the request to the parent class handler, and the subclass does not need to handle the work of delivery. The report is an abstract method, and the subclass must override the method, and the subclass handles the requested business logic. Setnexthandler is the hook method, which we did not implement here.

What are the benefits of combining template method patterns? First, the Handlemessage method is added, the transfer judgment of the request is stripped out of the subclass, and the sub-class concentrates on the business logic of the request in the report method, and achieves the single responsibility principle. Furthermore, the implementation of subclasses has become simpler, and there is no need to pass judgment, which is very helpful for rapid expansion.

Responsibility chain Mode vs Observer pattern

Observer Pattern I have had some before, I do not know can first look. There is a common denominator between the model of responsibility chain and the observer model, that is, the transfer responsibility chain mode is a first-level transfer, forming a chain, and the chain node (processor) has a transitive relationship . The observer pattern of the observer to the observer is not the transmission between the specific observer, there is no correlation between the observer . For the experience of the little Ape, in the chain of responsibility is the request from the technical manager to the boss, there is a hierarchical relationship, and for the observer pattern is from the Observer Small Ape issued, as the Observer's technical manager and boss will receive the small ape notice, is diffuse, technical manager and boss have no hierarchical relationship. This is the difference between the responsibility chain model and the observer pattern, and it is also the core of the responsibility chain model.

Iv. advantages and disadvantages of the responsibility chain model

1) Reduce coupling: The client does not need to know which processor the request is handled by, and the processor does not need to know the transitive relationship between the handlers, which is organized and distributed flexibly by the system.

2) Good extensibility: increasing the processor's implementation is simple, just rewrite the method that handles the request business logic.

Disadvantages

1) The request will be out of the chain hair until a handler responds, which can affect system performance when the chain of responsibility is longer.

2) Request recursion, debug troubleshooting more trouble.

Summarize

Responsibility chain mode in the actual project can be used in the place or more, such as the membership level system, the membership level constitutes a chain, the user initiates a request, the system as long as the request distribution to the responsibility chain mode of entry, until passed to the user membership level, so that the business logic of each member level will become very clear. This toss for a long time, mainly to the core of the chain of responsibility to explain clearly, so that everyone can easily understand, but also let me rethink the core of the chain of responsibility model. The next article is "Not ready", your point like and attention is my motivation oh, farewell!

Design mode java source github download :https://github.com/jetLee92/DesignPattern

My Java design pattern-the 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.