Design patterns to learn (at)

Written in 2019-11-13

Before the embankment before understanding design patterns:
goal one, the pattern is very important indicator of the serviceability of the program, like a one-time Demo program does not need to how high the maintainability;
2, recognize and acknowledge oriented interface the benefits of programming, does not endorse please look back at 1;
3, design patterns are decoupled nature of the fundamental means of decoupling is layered, the more sub-layers, the more the relationship is not intuitive;
4, do not affect the implementation of design patterns completely demand, just write code much, much reconstruction, read, read, also entered the "stereotype" design pattern.

Behavioral patterns

Template Method Pattern
Template Method is used a lot as a model, especially in the reconstruction of the system. When you are more than two of the same class, the code is almost exactly the same, only a little difference, we must consider whether to reconstruct a template method pattern. Parent will be a good algorithm steps typically change the portion of the package into the abstract method, the abstract method implemented by subclasses. From another perspective template method, in fact, it is an object-oriented complement polymorphic, Imagine, polymorphism is the parent class (interfaces) will be a good interface, sub-categories were realized, the reality may not always be so simple some are reusable parts, so that each subclass each repetition to achieve these reusable code is obviously problematic, it is to reconstruct this part of reusable code prefix to the parent to write a class that is You may, after that reconstruction is not yet applied template method? Drawback is the parent class calls the subclass method will increase the complexity of debugging.

Strategy Mode
Since it is the policy that is exposed to the caller that the caller needs to know what strategy. Oriented programming interface so that each may be replaced, partially encapsulated by variation strategy type, which means a thing can have multiple implementations, in a case where use is determined if ... else select a different scheme between the use of strategies can be considered under strategy pattern to replace. Use Strategy is very extensive, such as selecting Log4J clean-up strategy, strategy selection refused thread pool, and various third-party components to select a variety of internal policy at initialization, choose different strategies serialization protocol, and even some internal computational logic algorithm can also be packaged into different strategies. The essence of the strategy pattern lies closed for modification, be open for extension, there is only need to add a new policy and strategy class can use, whether there is need to use the lower number of policies that if my very stable, condition is very fixed case strategy pattern here? For example, my strategy is based, this can refer to the difference between simple factory and the factory model of the month (January to December), using a similar simple plant solutions based on gender (male, female, unknown three kinds), a wide approach taken appropriate policy based on gender or month, without the need to establish a number of policy class, but also the need for the caller exposure strategy, a more friendly to the caller, and second, to reduce complexity. Also do not order mode mode.

Chain of Responsibility pattern
Chain of Responsibility pattern is not new to us, think filter in web programming, Netty's handler are used in this mode. Chain of Responsibility pattern decouple the sender and receiver, a plurality of object a chance to handle the request. It is suitable for use under what circumstances the pattern here? First, there is the case of pipeline processing, handling every step of the chain equivalent to a node on the assembly line, part of the operation is completed, the other case is the presence of "pass the buck", and I could not deal with, to deal with the next house, the next house might He gave his next home treatment. All in all is the case of the need for application processing chain chain of responsibility pattern. The model brings disadvantages are: After chaining, are bound to have performance loss, especially when a long chain.

Observer pattern
between the subject an observer pattern defines many dependencies, so that changes state whenever an object, all objects that depend on it are notified and updated automatically. The observer pattern is often used to publish and subscribe model for comparison, first of all, publish the subscription model is not a formal design patterns, just because a distributed fashion, messaging middleware, Redis such as universal access, resulting in release subscription model is widely used; secondly, publish-subscribe pattern in the end be considered is the observer pattern? This problem is debated, but it is undeniable, it reaches the same observer pattern effect that: when an object changes state, all objects that depend on it are notified and updated automatically, or even more than it was observed by mode more completely decouple the publisher and the recipient of the message, so that both sides can be completely not need to know each other's existence. Why use the observer pattern here? For example, in a scene and register bonus plus-integral, if the mode is not used, process-oriented manner in order to write the code, the entire process is such that: first, the logic register; a second step of performing a logical reward; Step increased integration. If only the complete demand point of view the above approach without any problems. However, demand is constantly changing, scalable (modified) sex is a problem we have to face, if we are to increase the integration of new operational requirements for registration, and send coupons. That way you deal with a large probability becomes the second step implementation of incentive logic into gift vouchers logic, which violates the principle of opening and closing. If the observer mode, you only need to add a coupon gift objects, and subscribe to registered users of this Subject, the whole process does not modify user registration to this logic. If the message queue publish subscribe model, it is more simple, just to the message queue pub a message when a user registration is complete, registration for the event's focus on user objects may subscribe to the message queue and process itself.

State model
state model with state of the object corresponding to the operation implemented as a subclass of, for example, there are three operations are registered, credit, expended, three operations corresponding state are: unregistered, registered, credit has been . If ... else traditional judgment code structure is substantially: determining whether the user is not registered at the time of registration, or corresponding prompt; when credit determines whether the user has registered, or corresponding prompt; in expended when determining whether the user has credit, otherwise the corresponding prompt. Imagine if newly added one state, the registration, credit, disbursement of logic to do the appropriate changes. Reconstruction of the state pattern is generated after an unregistered, registered, credit has three state class, each class implements the state register, credit, expended these three methods, the state corresponding to the user specified by the caller, and when the new state corresponding to a state just add subclasses, without modifying the existing code logic. State pattern model is very similar structures and policies, the policy corresponding to the policy model is specified by the caller, the state model is a state corresponding to the caller and can be specified by the state switching, with a more general strategy pattern property. State mode where applicable in the presence of a plurality of state determination, if the presence of three or more layers if ... else code switch or a field of a branch condition is determined state value, may be considered to be reconstituted state mode.

Iterator pattern
isolated traversal behavior collection of objects, abstract an iterator class to be responsible, do not expose internal representation of the object. Collection in Java have achieved Iterator, daily business needs to achieve self-encoding local custom collection classes do much, if any, is the combination of Java Collection can also be defined by little internal exposure from the Java Collection classes to provide more easy access, such as support for syntax, so the daily programming of the application of this model is not much. However, due to the support of JDK class library, we are too commonplace for this use that to almost forget this is a design pattern. Benefits do not need to expose internal representation of the object, only need to add a new set of classes iteration when new collections, while also providing consistent access interface. The downside is a collection of classes and class iterations increases in pairs.

Intermediary model
agency is an old character, life is everywhere. Mediator pattern similar to the reality of the agency, its core is to change the mesh coupling relationship star couple relationship, thus reducing the direct coupling between the object and the object. Our most common MVC mode C is an intermediary class, the advantage is the decoupling of M and V, so that they can independently change. Such as chat rooms, if not a mediator (modeled as chat rooms), the relationship between the network that the user is a typical relationship, reflected in the code is the same for each user to hold another chat room user references , between the user and the user is so tightly coupled relationship, and the introduction of a mediator, that the decoupling of the tight coupling. Users need only a message to the mediator (chat rooms) it then message to the target user. There are two possible problems in the process of mesh into a star, the first question is a mediator selected too small, there is a mediator between every two objects in extreme cases, between the different intermediaries that they may produce the network association, but the relationship has become more complex. Another problem is that a mediator selected too large, in this case, too much responsibility intermediaries, resulting in a substantial increase in the number of interfaces. So intermediary model is usually used in a dialectical and attention with other design patterns in modeling.

Interpreter pattern
popular point that interpreter mode is used to resolve a string of text, such as to achieve their own expression evaluator can be achieved with the interpreter mode. Due to a variety of dynamic SQL scripts and applications, coding, and daily business use less need to customize the "grammar" of the place, so the pattern was little practical use. The advantage of high extensibility, increasing new class does not need to modify the old analytical parsing code. The core idea is to construct a syntax tree, the time for computing, recursive calls.

Memo mode
called the memo mode is without damage to the package, to capture the internal state of an object, and save the state outside of the object so that the object can be restored to a previously saved state in the future. We note in the memo mode and the reality which is very similar, it is used to achieve a design pattern memo or archive recovery. Imagine a scenario: You have an object Originator, the need to support certain fields of the object (not all) returned to the state on a certain point in time. A memo mode is implemented as follows: Since the object Originator only partial field is needed to support recovery, but also in order not to destroy its packaging, the need to introduce a memo Memento class, the object is responsible for storing Originator class all fields need to be stored, based on a single responsibility principle, and finally introduced Caretaker (managers) working class is responsible for saving the memo.

Command Mode
command mode decoupling of the caller and the recipient, so that they only rely on command Command, which can change independently, the new commands can be easily added to the system, to facilitate the achievement Command Queuing, also ease the implementation Undo and Redo operating. Command mode is the recipient of things to do, abstracted into a command, the command to decouple. In a specific command, the corresponding operation command with the recipient examples cited. Sender of this command is responsible for sending various commands. The sender may correspond to a same plurality of different recipients, the recipient can correspond to a different plurality of different senders. Our common action Struts is used in command mode, the workflow engine Activiti initiate the whole process of approval, circulation, variable settings are used to complete the command mode. Then how do we apply this model in everyday programming? When the caller does not correspond to a particular recipient or there is one pending further, the conventional method can not be used and calls one of the other referenced methods, and use the command mode contemplated at this time decoupling. Further, when it is desired to achieve the command queue to provide undo and redo, may be considered to use this mode.

Visitor pattern
visitors, as the name suggests, is to give an object to do with access. This is very strange: a visit with this object is not it? Internal access object is not a way to do this?
That with this.methodX () can not you do? Why add a single visitor class it? Imagine, if a class of structures (basic properties and methods) are stable, but access methods are easy to change, it is easy to change the part of visitors drawn to the class, when business change is not only need to modify visitors class on the line it? Is not reached "static and dynamic separation" effect of it? Demeter said that an object should be as little knowledge of other objects that visitors type (Visitor) is not to be a visitor class (Element) know too much? If the buckle detail, then do so is indeed a violation of the Law of Demeter, but if the Element and Visitor considered as a whole it? When the fixed type Element, the number of reload Visitor Visit access method is generally the same with the number of kinds of Element, Element and also has the formula given accept (interview) method. Visitors scene modes to adapt to more demanding: Element number and structure more stable, while access methods / algorithms and volatility may consider the use of visitors.

Guess you like

Origin www.cnblogs.com/mzsg/p/11978035.html