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

Go learns design patterns-decorators and chains of responsibilities. Which pattern is more scientific to implement middleware?

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > IT Information >

Share

Shulou(Shulou.com)11/24 Report--

Hello everyone, I am here every week to accompany you in the progress of the network manager ~, this time we continue to fill the hole, talk about the decorator mode.

In the last article, we said that decorators are special applications of proxy patterns, and many people say that middleware is implemented in decorator patterns, and some people say that they are implemented in chains of responsibilities, so let's take a look at their similarities and differences in this article.

What is the decorator pattern (Decorator Pattern), also known as the wrapper pattern (Wrapper Pattern), refers to dynamically adding some additional responsibilities to an object without changing the original object. In terms of added functionality, the decorator pattern is more flexible than generating subclasses and belongs to a structural design pattern.

The simplest and intuitive way to add new behavior to an object is to extend the ontology object and achieve the goal by inheritance. However, using inheritance inevitably has the following two disadvantages:

Inheritance is static, determined during compilation, and cannot change the behavior of the object at run time.

Subclasses can only have one parent class, and when there are too many new features to add, it can easily lead to a sharp increase in the number of classes.

Using the decorator pattern, we dynamically add new behavior to existing objects by placing them in wrapper objects that implement the same set of interfaces. Extending our code in the wrapper helps to reuse functionality without modifying the code of existing objects, in line with the "open-close principle".

The "existing object" that is placed in the wrapper object here is usually called "Component", and the wrapper object that wraps the component is what we often call "Decorator". Because the decorator will implement the same interface, the client cannot recognize the difference between the two, so there is no need to modify the client call code when adding the decorator.

From the above description of the decorator pattern, it will feel that it is very similar to the proxy pattern. This is because they are almost the same in structure, and the decorator is a special application of the agent-one of the features of the decorator pattern is that it can nest multi-layer decorators, which is equivalent to adding agents to the agent. However, the agent emphasizes the access control of ontology objects, while the decorator is used to enhance the local, the two are different in the purpose of use.

The usefulness of the decorator pattern above is described in words, so let's use the UML class diagram to show its structure to give us a clearer understanding of the roles in the pattern before writing the code.

The structure of the decorator is represented by the UML class diagram. The structure of the decorator pattern is as follows:

You can see from the figure that there are mainly the following roles in the decorator mode:

Client: the component is encapsulated with a multi-layer decorator, and finally the method of the decorated wrapper is called to start execution.

Component interface: Component declares the common interface to be implemented by the decorator object and the decorated component object.

Component implementation: the specific component implementation class defines the underlying behavior of the component in its Operation method, and decorating classes can enhance these behaviors.

Base Decoration Class: has a member variable that points to the encapsulated object. Call the Operation method of the decorated object in your own Operation method

Specific decoration class: override the Operation method of the parent class to implement enhanced logic. The main logic to be implemented has been given in the class diagram. the basic decoration class in step 4 does not need to exist, and the specific decoration class can hold the reference to the decorated object and implement the enhanced logic. in this way, the overall structure will be simpler.

Note: the method name in the figure can be defined by itself in the code implementation and does not need to be exactly the same as the method name given in the figure.

We can compare with the UML class diagram of the proxy pattern in the previous section, the two are very similar in structure, especially after omitting the BaseDecorator layer, the structure is basically the same, so we have been emphasizing that "decorator is a special application of proxy pattern" argument.

Let's take a look at the code template that implements the decorator pattern. This article provides a code template for the Go language to implement a simple decorator pattern.

After the decorator pattern code implementation is clear about the composition of the decorator pattern structure, it will be much clearer to write the code. Next, let's demonstrate an example of using the decorator pattern to enhance the game console.

First of all, we define a product interface for the game console, which is the common interface for the components and decorators in the class diagram above.

/ / PS5 product interface type PS5 interface {StartGPUEngine () GetPrice () int64} then we provide a basic product implementation class as a component in the decorator pattern.

/ / CD version of the PS5 host "the complete runnable source code used in this article goes to the official account" Network Manager bi says "send [Design pattern] and you can get" type PS5WithCD struct {} func (p PS5WithCD) StartGPUEngine () {fmt.Println ("start engine")} func (p PS5WithCD) GetPrice () int64 {return 5000} what is given here is a CD version of the game console. Students who usually play games will know that there will generally be a digital version of the host, and the price will be cheaper. In this case, we can provide a digital version of the game console implementation as a component implementation class.

/ / PS5 digital host type PS5WithDigital struct {} func (p PS5WithDigital) StartGPUEngine () {fmt.Println ("start normal gpu engine")} func (p PS5WithDigital) GetPrice () int64 {return 3600}, in addition to these two basic product types, manufacturers generally develop hosts with limited colors on various themes, hosts with hardware configurations, and so on, which will certainly be somewhat different from the basic version in price. For this level of extension, we can use decorators to avoid changes to the underlying component classes.

Here are two enhancements to the Plus version and the theme color version implemented with two decorators.

"the complete runnable source code used in this article goes to the official account" bi says "send [design pattern] and you can get the Plus version of the decorator func (p * PS5MachinePlus) SetPS5Machine (ps5 PS5) {p.ps5Machine = ps5} func (p PS5MachinePlus) StartGPUEngine () {p.ps5Machine.StartGPUEngine () fmt.Println (" start plus plugin ")} func (p PS5MachinePlus) GetPrice () int64 {return p.ps5Machine.GetPrice () + 500} / / theme color plate Decorator type PS5WithTopicColor struct {ps5Machine PS5} func (p * PS5WithTopicColor) SetPS5Machine (ps5 PS5) {p.ps5Machine = ps5} func (p PS5WithTopicColor) StartGPUEngine () {p.ps5Machine.StartGPUEngine () fmt.Println ("distinguished theme color host" GPU launch ")} func (p PS5WithTopicColor) GetPrice () int64 {return p.ps5Machine.GetPrice () + 200} according to the characteristics of the decorator mode, the two enhancements can also be superimposed to form a high-configuration theme limited edition host. Er, is it a bit like the feeling given to you by a big game manufacturer when it sends new machines every year, that is, the second generation will send you a few more limited colors and upgrade the screen every year, that is, you are XXX (make up your own comments)

Well, on the client side, we combine decorators and components to get a high-end theme limited version of the host.

"the complete runnable source code used in this article goes to the official account," bi says, "send [Design pattern] and you can get" func main () {ps5MachinePlus: = PS5MachinePlus {} ps5MachinePlus.SetPS5Machine (PS5WithCD {}) / / ps5MachinePlus.SetPS5Machine (PS5WithDigital {}) / / you can change the host ps5MachinePlus.StartGPUEngine () price: = ps5MachinePlus.GetPrice () fmt.Printf ("PS5 CD Deluxe Plus version" Price% d yuan\ n\ n ", price ps5WithTopicColor: = PS5WithTopicColor {} ps5WithTopicColor.SetPS5Machine (ps5MachinePlus) ps5WithTopicColor.StartGPUEngine () price = ps5WithTopicColor.GetPrice () fmt.Printf (" PS5 CD deluxe Plus classic theme color version, price% d yuan\ n ", price}

The difference between the decorator and several patterns the decorator and the agent are similar in structure and behavior is similar to the chain of responsibility pattern. Now let's summarize the differences between them.

Decorator pattern VS proxy pattern decorator pattern is a special application of proxy pattern.

The decorator mode emphasizes the extension of its own functions.

The agent model emphasizes the control of the agent process.

Decorator VS chain of responsibility pattern decorator and chain of responsibility in behavior are multiple units combined to complete logical processing, but the decorator focuses on adding extensions to something and ends up with a product. On the other hand, the responsibility chain emphasizes completing a process step by step, which is more like a task linked list, and unlike the decorator pattern, the responsibility chain can be terminated at any time.

For example, for the OA system leave approval scenario, it is assumed that employees need to be approved by the team leader, director, and manager. In this case, using the decorator pattern, whether your leave is approved or rejected in the previous link, the whole chain will not be interrupted, and eventually we will get full feedback from the three levels of approvers on the application.

Using the chain of responsibility model, each approver has the right to approve or reject at each stage. If the request is rejected at any level, the entire process ends and the request does not continue to flow to the next level of approver.

So looking at this, do you think something like the middleware of the Web framework should be implemented with a chain of responsibilities or a decorator?

The summary decorator pattern has many advantages. It is a powerful supplement to inheritance and is more flexible than inheritance. It dynamically extends the function of an object, namely plug and play, without changing the original object. Through the use of different decoration classes and the arrangement and combination of these decoration classes, different effects can be achieved and the "opening and closing principle" of programming can be fully followed.

However, the use of the decorator will certainly bring higher complexity and lower readability to the program, the code structure of subclass integration will be more straightforward and easier to understand, and although the decorator conforms to the "opening and closing principle", it will bring more classes to the program. Dynamic decoration is more complex in multi-layer decoration.

Therefore, in general, when using the decorator mode, we choose the lesser of the two evils, and introduce more decorator classes in order not to modify the formed subclasses frequently.

When you apply it, you must keep in mind that the decorator is used to "enhance" something, but never realize the main logic of the thing itself with the decorator.

This article comes from the official account of Wechat: bi ID:kevin_tech, author: KevinYan11

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

IT Information

Wechat

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

12
Report