Learn design patterns from Meituan (feelings)

After reading this article, I discovered that your thoughts and thinking are really stronger than the technology you possess.

Note 

open-close principle

The Open-Closed Principle is one of the basic principles in object-oriented design. Its definition is: a software entity should be open to extension and closed to modification. That is to say, during the life cycle of the software, when the software needs to be modified, the change should be achieved by extending the behavior of the software entity rather than by modifying the existing code.

The purpose of the open-closed principle is to improve the reusability and maintainability of software. During the software development process, software requirements may change as business requirements change, and the open-close principle can help us avoid modifications to existing code, thereby reducing the risk of introducing new errors and reconstructing the entire function.

Demeter's Law

The Law of Demeter (LoD) is an object-oriented design principle, also known as the Least Knowledge Principle (LKP). It states that a software entity should interact with other entities as little as possible. If a system complies with Demeter's Law, then when one of the modules is modified, it will affect other modules as little as possible, and expansion will be relatively easy. This is a restriction on communication between software entities. Demeter's Law requires restrictions. The breadth and depth of communication between software entities.

The core idea of ​​Demeter's Law is to reduce the coupling between components and improve the loose coupling of the code, thereby making the code easier to maintain, expand and refactor. Under the guidance of Demeter's Law, a class should interact with other classes as little as possible and try to avoid direct interdependence. Instead, it communicates through mechanisms such as interfaces and abstract classes to make the connection between classes More loose, easier to maintain and extend.

The Law of Demeter is named after the character Demeter in ancient Greek mythology. She is the goddess of agriculture in Greek mythology and the sister of Zeus. In this myth, Demeter stipulates the laws of agricultural production, similar to how Demeter's laws stipulate the rules of communication between software entities.

Focus on the two aspects of high cohesion and low coupling, and then combine design patterns

Focus on the two aspects of high cohesion and low coupling, and then combine design patterns

Focus on the two aspects of high cohesion and low coupling, and then combine design patterns

Reward distribution strategy

On the first day, the teacher asked Xiao Ming: "Do you know about event marketing?" "
I know that event marketing refers to companies that participate in existing activities that attract high social attention, or integrate effective
resources independently plan large-scale activities, thereby quickly To improve the visibility, reputation and influence of the company and its brand, common
ones include lottery draws, red envelopes, etc."
The teacher nodded: "Yes. Let's assume that we are going to do a marketing now, which requires users to participate in an activity and then
complete a task. For a series of tasks, you can finally get some rewards in return. The rewards of the event include
coupons for various categories such as Meituan takeout, wine travel and food. Now I need your help to design a reward distribution plan."
Because I have similar development experience before After getting the requirements, Xiao Ming started writing the code without saying anything:

 Xiao Ming quickly wrote the demo and sent it to the teacher.
"If we are about to add new taxi tickets, does this mean you have to modify this part of the code?" the teacher
asked.

The scrutiny is evident at a glance. This does not satisfy the opening and closing principle and the Dimit principle in our design principles.

So how do we optimize it?

In this case, you can use adapter and strategy patterns to tune

Strategy Mode | Rookie Tutorial    Adapter Mode | Rookie Tutorial

First, it is optimized through this strategy pattern and becomes the following code

 Then, Xiao Ming creates the environment class of the strategy mode and calls it to the reward service:

After Xiao Ming's code has been optimized, although the structure and design are much more complicated than before, it is still very worthwhile considering its robustness and scalability.

Is the strategy class a stateful model? If not, can we consider making it a singleton?

The responsibilities of the environment class's acquisition strategy method are very clear, but they are still not completely closed to modifications.

Solution: The strategy class can be singletonized to reduce overhead, and the self-registration function can be implemented to completely solve branch judgment.

Xiao Ming lists the key points of the singleton pattern:
Singleton pattern Design pattern is a creational pattern, which provides the best way to create objects.
This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is
created. This class provides a way to access its unique objects directly, without the need to instantiate an
object of the class.

 Finally, Xiao Ming uses a registry in the policy environment class to record the registration information of each policy class, and provides an
interface for the policy class to call for registration. At the same time, use the Hungry-style singleton pattern to optimize the design of the strategy class:

 

 

Finally, the structural class diagram completed by Xiao Ming is as follows:

If you use the Spring framework, you can also use Spring's Bean mechanism to replace part of the above design. You can
directly use @Component and @PostConstruct annotations to complete the creation and registration of singletons, and the code
will be more concise.

Some thoughts of my own

When designing your business logic, or writing your logic code, you must think about design patterns - creative patterns, structural patterns, and behavioral patterns, as well as the following

J2EE Patterns
These design patterns focus specifically on the presentation layer

What should we use. How to tune

Design of task model

Now, I want you to complete the design of the task model. You need to focus on status transition changes and message notifications after status changes. The previous reward distribution strategy seems to be a determination of status.

Xiao Ming took over the problem. He first defined a set of task status enumerations and behavior enumerations.

Then, Xiao Ming started writing the status change function

Obviously the above code still has the same problem as the previous example.

what is the problem

First, conditional judgments are used in the method to control statements. However, when the conditions are complex or there are too many states, the conditional judgment
statements will be too bloated, have poor readability, are not scalable, and are difficult to maintain. And when adding a new state
, a new if-else statement must be added, which violates the opening and closing principle and is not conducive to program expansion.

Second, the task class is not cohesive enough. It perceives
the models of other fields or modules in the notification implementation, such as activities and task managers. In this way, the coupling degree of the code is too high, which is not conducive to expansion.

optimization

Firstly, the state pattern can be used to control state flow. Secondly, the observer pattern can be used to notify when a task is completed.

Observer Mode | Rookie Tutorial Status Mode | Rookie Tutorial

According to the definition of the state pattern, Xiao Ming extended the TaskState enumeration class into multiple state classes and had
the ability to complete the flow of states; then optimized the implementation of the task class:

 Xiao Ming was pleased to see that the coupling degree of the task class processed by the state mode was reduced, which was in line with the opening and closing principle.
The advantage of the state model is that it conforms to the single responsibility principle, the state class responsibilities are clear, and it is conducive to program expansion. The cost of this design is that the number of state classes increases. Therefore, the more complex the state flow logic is and the
more actions need to be processed, the more conducive it is to the application of the state pattern.

Xiao Ming first designed the abstract target and abstract observer, and then customized the notification receiving function of the activity and task manager
into a specific observer:

 Finally, Xiao Ming optimized the task progress status class to use a common notification method, and
defined the observers required for the task progress state when the task initial state execution state flows.

 

Finally, the structural class diagram completed by Xiao Ming is as follows:

 Through the observer pattern, Xiao Ming allows the task status and the notifier to achieve loose coupling (in fact, the observer pattern has not been able to achieve complete decoupling. If you want to further decouple, you can consider learning and using the publish-subscribe pattern)

Iterative reconstruction of activities

The characteristic of the activity model is that it has many components. Xiao Ming’s original activity model was constructed like this

 

The problems with the above code are mainly manifested in

There are many active construction components, resulting in too many constructors that can be combined, especially when adding fields to the model, the
constructors need to be modified.

There is a certain order relationship in the construction of some components, but the current implementation does not reflect the order, resulting in
confusing construction logic and some duplicated code.

What about this situation? We use creator pattern.

In actual applications, if there are many field types
and each field only needs simple assignment, you can directly reference Lombok's @Builder annotation to implement a
lightweight builder.

After reconstructing the design of the event construction, Xiao Ming began to add risk control to the method of participating in the event. The simplest way is definitely

Directly modify the target method. However, some activities require risk control and some do not. At this time we use the decorator pattern. for risk control.

Guess you like

Origin blog.csdn.net/qq_52988841/article/details/132305449