Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to master the responsibility chain of design pattern

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to master the responsibility chain of design patterns". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to master the chain of responsibility in design patterns".

Examples

Suppose you also "cross" to the Qing Dynasty, is to write the code of the Hexi and Zhongtang, the emperor will immediately tour the south. Please use the code to encapsulate and simulate "Qianlong Xia Jiangnan".

How are you going to arrange your itinerary? You know, this is a big project, there can be no mistakes in the middle, if something goes wrong, you will lose your head.

However, the emperor is also a man of temperament, and his itinerary may often be changed, or even make a private visit halfway.

Therefore, when we serve the emperor to the south of the Yangtze River, we should not only allow the emperor's itinerary to proceed in an orderly manner, but also try our best to adapt to the changes that may be made by the emperor on a whim.

How to design it? If you write all the emperor's itinerary together, there are two disadvantages:

There's too much itinerary, and it's all important. You have to take care of it all by yourself. If something goes wrong, you have to move your head.

There is a lot of itinerary, so it is too troublesome to add and correct, and it is easy to mess up if you change the itinerary of the holy. After all, the itinerary is written together, like a mess and a mess.

So the question is, how can you arrange the itinerary of the saint with your excellency?

If you look at the map, you can see that Qianlong will go through Zhili, Shandong, Jiangsu and Zhejiang provinces from Beijing to Hangzhou (basically the current Beijing-Shanghai high-speed railway):

In this way, the adults can roughly divide the task into four parts according to the province, instruct the officials of the four provinces to share this big project, connect their responsibilities into an orderly chain, and then let them carry out the task of serving the emperor in turn.

On the one hand, it solves the problem that the itinerary is too rich and cannot be arranged by adults alone; second, it ensures the flexible arrangement of each step (described in the following example), and third, it is easy to be held accountable for which step has gone wrong (throw the pot, otherwise it's all your own fault).

All right, after all that has been said, let's cut to the technical level.

Design

Step1:

First of all, let's summarize the nouns in the problems we study to determine which categories are needed:

Emperor (Qianlong)

The manager of the trip (and the atrium)

Provincial officials (public servants who work specifically)

Step2:

Then determine the relationship between the various classes:

The easiest thing to see is that provincial officials are colleagues, and they all have to receive Qianlong, but the order of appearance and the specific reception behavior during the emperor's southern tour are different, such as:

The governor of Zhili will take Qianlong to the summer resort.

The Shandong Patrol Association gathered the emperor to worship the Confucius Temple.

Suzhou Weaving allows the Emperor to visit the Garden

And Hangzhou Zhizhou took the emperor to the Sudi of the West Lake.

Here is a small formula for optimizing design in OOD: changing the pumping interface, the same modeling version.

So we are here to face the different behavior of officials, it is best to abstract them into interfaces or abstract classes, here we use the abstract class of officials (Official).

As the chief administrator, he should not only control the movements of emperors, but also control provincial officials, so at the class level and PrimeMinister, there must be references to the list of emperors (Emperor) and officials.

The UML diagram is shown below.

UML diagram

Colleagues from all provinces:

And you and your excellency, as the celebrities in front of Qianlong, have to make overall arrangements for the emperor's itinerary, not only to kidnap the emperor, but also to be in charge of provincial officials, so that they can carry out their tasks in an orderly manner:

The chain of responsibility generally has at least one processed object, which is passed into each step as a parameter, and Qianlong here is the object to be processed (served).

Code

As an abstract class of officials, we take into account the actual situation, he has to arrange a place and accompany the emperor to visit and visit, in fact, it is a sentence: serve the emperor.

So he has an abstract method, serve, to accept the object of the Emperor.

@ Data public abstract class Official {protected String title; protected abstract void serve (Emperor emperor); @ Override public String toString () {return title;}}

Here, in order to distinguish between different officials, we also give the official (Official) class a member variable title.

There are concrete classes under Official, representing provincial officials, who have their own specific ways to serve the emperor, such as the governor of Zhili, as he did:

Public class HebeiOfficial extends Official {public HebeiOfficial () {this.title = "Governor of Zhili"; @ Override protected void serve (Emperor emperor) {emperor.play (this, "Summer Resort");}}

Here in serve, the parameter "emperor" is completely left to decide how to play. (by the way, this way of letting the parameter, an "exotic monk", recite the sutra, is very common in various design patterns. If you replace the Emperor here with Comparator, I believe many friends will feel a bit like the strategy mode. Moreover, the "Governor of Zhili" can also do some things before or after the Emperor play. Is this like the way InvocationHandler treated Method when he used the agent of JDK? Or the handling of Aspect in Spring? In addition, you can also see this way of writing in design patterns such as Visitor)

Other officials write in a similar way, only to find another place for the emperor to visit. See the output results below, which are briefly described here.

As an emperor, Qianlong can only play. Of course, you and the atrium can arrange for local officials to accompany you, so there is only one play method for emperors. Here, a string is used to simply indicate the place to visit.

In order to prevent the establishment of another "new emperor" (implementing new Emperor ()) in Beijing during Qianlong's southward journey, the creation process of this "emperor" object adopts a singleton mode to ensure that there is only one emperor in the whole JVM, and the name is "Qianlong":

Public class Emperor {private static final Emperor INSTANCE = new Emperor ("Qianlong"); private final String name; private Emperor (String name) {this.name = name;} public static Emperor getInstance () {return INSTANCE;} public void play (Official official, String place) {System.out.println (official.getTitle () + "arrangement" + name + "Emperor Tour:" + place) }}

And you, Hefei and your excellency, only need to arrange the following officials reasonably according to the order of the provinces, and then invite the emperor and announce to the world: once the saints are in the south of the Yangtze River, all the provinces along the way should take care of them:

Public class PrimeMinister {private static List list = new ArrayList (); public static void main (String [] args) {/ / order provincial officials along the way to prepare list.add (new HebeiOfficial ()); list.add (new ShandongOfficial ()); list.add (new JiangsuOfficial ()); list.add (new ZhejiangOfficial ()); / / the emperor Emperor emperor = Emperor.getInstance () / / tell the world: long live to drive down to the south of the Yangtze River! Along the way, the provinces served the holy System.out.println ("Qianlong Xia Jiangnan!"); start (list, emperor);} private static void start (List officials, Emperor emperor) {for (Official o: officials) {o.serve (emperor);}

See if your task is much more concise. You just need to maintain the roster of provincial officials along the way.

More importantly, you don't have to be responsible for it yourself. the people below who are incompetent will have their heads!

As long as our "roster" or "itinerary" is written correctly, our head will be saved.

Moreover, the tasks of various officials are relatively simple, and they are less prone to mistakes themselves. The following is the implementation of the entire trip simulation:

Qianlong went to the south of the Yangtze River!

The governor of Zhili arranged for Emperor Qianlong to visit the Summer Resort.

The governor of Shandong arranged for Emperor Qianlong to visit the Confucius Temple in Qufu.

Suzhou weaving arranged for Emperor Qianlong to visit: Suzhou Gardens

Hangzhou Zhizhou arranged a tour of Emperor Qianlong: the Su Embankment of the West Lake

Well, everything seemed to be all right, and the provincial officials completed the task in order, and served him well, and nothing unusual happened, so he breathed a sigh of relief.

However, now there is an emergency: the emperor suddenly asked to add a link when passing through Shandong-a three-day tour by Daming Lake!

Why did you go there on purpose? We dare not ask! Just get ready.

Fortunately, we already have a general framework for our itinerary. Hurry up and find out who is in charge of Daming Lake. Oh, he is the magistrate of Jinan!

Now we only need to add him to the roster: order the magistrate of Jinan to arrange the emperor's three-day itinerary on the bank of Daming Lake, and there must be no mistake, otherwise I will try to ask you! Here are the changes to be made with adults:

... The above is slightly. List.add (new HeibeiOfficial ()); / / join Jinan magistrate and let him work. He knows how to play list.add (new JinanOfficial ()); list.add (new ShandongOfficial ()); list.add (new JiangsuOfficial ()); list.add (new ZhejiangOfficial ()) on the banks of Daming Lake. The following is a brief description.

On the other hand, the magistrate of Jinan is also a member of the bureaucratic system (a subcategory of Official), so he should also do his best to make the Holy Master have a good time on the banks of Daming Lake:

Public class JinanOfficial extends Official {public JinanOfficial () {title = "Jinan magistrate";} @ Override protected void serve (Emperor emperor) {emperor.play (this, "Daming Lake");}}

Execute the program again to simulate the itinerary of the Holy one, and the output is as follows:

Qianlong went to the south of the Yangtze River!

The governor of Zhili arranged for Emperor Qianlong to visit the Summer Resort.

Jinan magistrate arranged for Emperor Qianlong to visit the banks of Daming Lake.

The governor of Shandong arranged for Emperor Qianlong to visit the Confucius Temple in Qufu.

Suzhou weaving arranged for Emperor Qianlong to visit: Suzhou Gardens

Hangzhou Zhizhou arranged a tour of Emperor Qianlong: the Su Embankment of the West Lake

Well, this finally caters to the holy will, and the emperor will not be afraid of any other itinerary in the future (as long as he does not make a private visit, you go to Ji Xiaolan, ah, the principle of single responsibility, is it not for special things?)

As long as you find a specific local official, a piece of order: you give me the best to entertain the emperor, specific how to entertain, you decide to do, do not serve a good master, I want your head!

Of course, the emperor may also temporarily delete a link in the southern tour, we can just delete it from the itinerary list, and when we want to re-add it, you can add it at any time, so that you can "flexibly plug in". The changes to the code are reduced to a minimum, and when new business logic is added, it is only added, which is not prone to errors and ensures the flexible expansion of the code. And the steps in the current chain of responsibility, if there is no state-related information, can also be assembled into other chains of responsibility.

If it is our real project, we can even configure the list of work steps in the Spring Boot configuration file, open this class of the process, just read the configuration, and then execute each step in turn.

In this way, if there are changes, just change the configuration file, and there is no need to make any changes in the Java code.

Summary and expansion

In fact, the above is just the simplest application of the chain of responsibility model, which is an ordered list of steps for each task, and then runs to the end.

We can write it in our own program, or we can abstract it into a product, allowing others to expand and configure freely to minimize repetitive manufacturing of wheels.

This is true of many workflow engines, such as Activiti, Netflix's Conductor, and so on. Not only that, even your most commonly used SpringMVC and even Tomcat use the chain of responsibility model, but their chain of responsibility is bi-directional, dealing with requests and responses separately, and their processing order is just the opposite, essentially traversing the array (Filter or Interceptor) in reverse order using a similar recursive method.

In addition, in some continuous integration and continuous deployment frameworks, such as Jenkins, there will be the concept of Pipeline, when you make the git push commit code, it will trigger the whole process to operate step by step: pull the code (Checkout code), build (Build), test (Test), etc., until the deployment (Deploy) is complete and run the script to shut down the old version of the service and start the newly deployed service. This "Pipeline" is also a chain of responsibility that allows you to configure with code scripts.

Without the application of the chain of responsibility mode, you can't even run any Java programs. Because class loading generally follows the "parent delegation" mechanism, it actually uses similar recursive methods to traverse the linked list formed by the Classloader class once in positive and reverse order (beside the point, if you want to flip a linked list, you can see what Sister Qi wrote before:), but the logic is more complex, and the design pattern of "template method" is also applied. Since this article is only a simple introduction to the chain of responsibility model, these do not expand too much.

At this point, I believe you have a deeper understanding of "how to master the chain of responsibility of design patterns". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report