Thoughts on design pattern

Source: Internet
Author: User

1. Simple Factory mode

Sentiment: The factory class contains the necessary logical judgments, dynamically instantiating the related classes according to the client's selection criteria, and for the client, to remove the dependence on the specific product.

2. Policy mode
Definition: It defines the algorithm family, separately installed, so that they can replace each other, this mode allows the algorithm changes, will not affect the use of the algorithm of the customer.
Sentiment: The strategy pattern is a method to define a series of algorithms, conceptually, all of these algorithms do the same work, but the implementation is different, it can call all the algorithms in the same way, reducing the various algorithm classes and the use of the coupling between the algorithm classes. The strategy class hierarchy of the policy pattern defines a series of reusable algorithms or behaviors for the context, and inheritance helps to break out the public functions in these algorithms while simplifying unit testing, because each algorithm has its own class that can be tested individually on its own pretext.
Use scenario: The policy pattern is used to encapsulate the algorithm, but in practice we find that it can be used to encapsulate almost any type of rule, as long as the analysis process to hear the need to apply different business rules at different times, you can consider the possibility of using the policy model to deal with this change

3. Single responsibility principle (SRP)
Definition: As far as a class is concerned, there should be only one cause for it to change.
Sentiment: If a class takes on too much responsibility, it is tantamount to coupling these responsibilities, and a change in responsibility may weaken or inhibit the ability of the class to perform other duties. This coupling leads to fragile designs that can be subjected to unexpected damage when changes occur. The real thing about software design is to discover responsibilities and separate those responsibilities from each other. If you can even think of more than one motive to change a class, then this class has more than one responsibility.

4. Open-Close principle
Definition: means that software entities (classes, modules, function waits) should be extensible, but not modifiable.
Feel: No matter how close the module is, there will be some changes that cannot be closed to it. Since it is impossible to be completely closed, the designer must choose which of the modules he designed should be closed. He must first guess what kind of change is most likely to occur and then construct an abstraction to isolate those changes. When we first wrote the code, we assumed that the change would not happen. When changes occur, we create abstractions to isolate similar changes that have changed in the future. In the face of demand, changes to the program are made by adding new code, rather than changing the existing code. What we want is to know the changes that may occur soon after the development work unfolds. The longer you wait to find out what changes may occur, the more difficult the abstraction to create.
Advantages: The open-close principle is the core of object-oriented design. Following this principle can lead to the huge benefits claimed by object-oriented technology, which can be maintained, extensible, ready to take, and flexible. Developers should abstract only those parts of the program that are showing frequent changes, but it is also not a good idea to deliberately abstract each part of the application. Rejecting immature abstractions is as important as abstraction itself.

5. Dependency reversal principle
Definition: High-level modules should not rely on the underlying module. Two should all rely on abstraction. Abstractions should not depend on detail, and detail should be dependent on abstraction.
The Richter substitution principle (LSP)
Definition: subtypes must be able to replace their parent types.

Feeling: For the interface programming, do not implement programming only if the subclass can replace the parent class, the function of the Software unit is not affected, the parent class can be really reused, and the like can also add new behavior on the basis of the parent class. Because of the principle of the substitution of the Richter scale, opening-closing became possible. It is because of the substitution of subtypes that a module using the parent class type can be extended without modification. Dependency reversal can be said to be the object-oriented design of the logo, in which language to write the program is not important, if the writing is to consider how to focus on abstract programming rather than the details of programming, that the program all the dependencies are terminated in the abstract class alive interface, that is the object-oriented design, the reverse is the process of design.

6. Decoration mode
Definition: To dynamically add some additional responsibilities to an object, the adornment pattern is more flexible than generating subclasses in terms of adding functionality.

Sentiment: component is the definition of an object interface that can dynamically add responsibilities to these objects. Concretecomponent is to define a specific object, or to add some responsibility to the object. Decorator, decorate abstract class, inherit component, extend the function of component class from outer class, but for component, there is no need to know the existence of Decoratotrde. As for the concredecorator is the specific decorative objects, play to the component to add responsibility functions. The adornment mode uses the Set component to wrap the object. In this way, the implementation of each decoration object and how to use this object separated, each decorative object only care about their own functions, do not need to care about how to be added to the object chain.
Usage Scenario: Adornment mode is a way to dynamically add more functionality to an existing feature. When the system needs new functionality, it is adding new code to the old class, which usually decorates the core responsibilities or main actions of the original class, adding new fields, new methods, and new logic to the main class, thus increasing the complexity of the main class. And these new things are just to meet the needs of some particular behavior that is intended to be performed in a particular situation, but the adornment pattern provides a good solution, which puts each function to be decorated in a separate class and lets the class wrap the object it is decorating, so that when special behavior needs to be performed, The customer code can be used to Xu Zedi and sequentially use the decoration function to wrap objects as needed.
Pros: Remove functions from classes to simplify the original class. Effectively separates the core responsibilities of the class from the decorative functional areas. It can also remove repetitive decorative logic from related classes.

7. Proxy mode
Definition: Provides a proxy for other objects to control access to this object.

Usage Scenario: A remote proxy, which provides a local representation of an object in a different address space. This hides the fact that an object exists in a different address space, and virtual proxies create objects that are expensive to use as needed. It is a real object that takes a long time to instantiate, and the security agent is used to control the permissions of the real object when it is accessed; Intelligent guidance refers to the agent handling other things when invoking real objects.

8. Factory Method Mode
Definition: Defines an interface for creating objects, so that subclasses decide which class to instantiate. The factory method defers the instantiation of a class to its subclasses.

Sentiment: The difference between a simple factory model and a customer's need to decide which factory to instantiate to achieve the decision of the Operation class selection is still there, that is, the factory method moves the internal logic judgment of the simple factory to the client code. You want to add the function, originally changed the factory class, and now is to modify the client.

9. Prototype mode
Definition: Specify the kind of objects created with the prototype instance, and create new objects by copying these prototypes

Idea: The prototype pattern is actually the creation of another customizable object from one object without the need to know the details of any creation.

10. Template Method Mode
Definition: Defines an algorithm skeleton in an operation, and delays some steps into subclasses. The template method allows subclasses to redefine some specific steps of an algorithm without altering the structure of an algorithm.
Feelings: The template method mode is to remove the invariant behavior to the superclass, removing the duplicate code in the subclass to reflect its advantages, provides a good code reuse platform, when the invariant and variable behavior in the implementation of the subclass of the method is mixed together, the invariant behavior will be repeated in the sub-class, These behaviors are moved to a single place by means of the template method mode, which helps the subclass to get rid of the entanglement of repeated invariant behavior.

11. Dimitri Law
Definition: If two classes do not have to communicate directly with each other, then these two classes should not have a direct interaction, if one of the classes needs to invoke a method of another class, you can forward the call through a third party.
Feeling: In the class structure design, each class should try to reduce the member's access rights, the fundamental idea is to emphasize the coupling between the classes. The weaker the coupling between classes, the more beneficial it is to reuse, and a class that is in a weak coupling is modified without affecting the related classes.

12. Appearance mode
Definition: Provides a consistent interface for a group in a subsystem that defines a high-level interface that makes this subsystem easier to use.


Usage scenarios: First of all, in the initial phase of the design, you should consciously separate the different two layers, such as in the classic three-tier architecture, you need to consider the data access layer and the business logic layer, the business logic layer and the presentation layer between the layers and layers to establish the appearance of facade, for the auxiliary subsystem to provide an omelette interface, and In the development phase, subsystems tend to become more and more complex due to the evolution of continuous refactoring, increasing the appearance of facade can provide an egg-frying interface, reducing their dependence. Thirdly, when maintaining a legacy large system, it is possible that this system is already very difficult to maintain and extend, developing an appearance facade class for the new system, which provides a relatively clear and simple interface for designing coarse or highly complex legacy code, allowing the new system to interact with the facade object, Facade interacts with legacy code for all complex work.

13. Builder Mode
Definition: Separates the construction of a complex object from its representation, allowing the agreed build process to create different representations.

Sentiment: Builder is an abstraction interface for creating individual parts of a Product object, ConcreteBuilder is a concrete builder, implements the builders interface, constructs and assembles individual parts. Product is, of course, the specific role. The director is the building of an object that uses the builder interface, which is primarily used to create complex objects that are usually built in a stable order, but often have complex changes built into the inside of the object. The benefit of the builder model is that the construction code is separated from the presentation code, because the builder hides how the product is assembled, so if you need to change the internal representation of a product, you just need to define a specific build. The builder pattern is when the algorithm that creates the complex object should be independent of the part of the object and the mode in which they are assembled.

14. Observer Pattern
Definition: This pattern defines a one-to-many dependency that allows multiple observers to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to automatically update themselves.

Feeling: Splitting a system into a series of collaborative classes has a bad side effect, that is, the need to maintain consistency between related objects, we do not want to maintain consistency and the various types of tight coupling, which will cause maintenance, expansion and reuse of the inconvenience. While the key object of the observer pattern is the subject subject and the Observer observer, a subject can have any number of observer that depend on it, and once the subject state has changed, all observer can be notified. Subject does not need to know who the observer is when it notifies, that is, the specific observer who, it does not need to know at all. And any particular observer does not know or need to know the existence of other observers.
Usage Scenario: When an object's changes need to change other objects at the same time, and it doesn't know how many objects to change, you should consider using the observer pattern. When an abstract model has two facets, one on the other hand, the observer pattern allows the two to be encapsulated in separate objects to be independently changed and reused. In general, the work of the observer pattern is actually decoupling. Let both sides of the coupling rely on abstraction, rather than relying on specifics. So that their changes will not affect the other side of the change.

15. Abstract Factory mode
Definition: Provides an interface to create a series of related or interdependent objects without specifying their specific classes.

Thoughts: abstractproducta and ABSTRACTPRODUCTB when two abstract products, because they are likely to have two different implementations, ProductA1, ProductA2, ProductB1, ProductB2 is the implementation of the specific classification of two abstract products, Abstractfactory is an abstract factory interface, it should contain all the product creation of abstract methods, and ConcreteFactory1 and ConcreteFactory2 are concrete factories. It is common to create an instance of the Concretefactory class at run time, and the specific factory creates a specific implementation of the Product object, that is, to create different product objects, the client should use a different specific factory.
Pros: The biggest benefit is the ease of exchange of the product family, because the specific factory class, in one application only need to initialize the time to appear once, which makes it very easy to change the specific factory of an application, it only need to change the specific factory can use different product configurations. The second advantage is that it allows specific instances of the creation process to be separated from the client, the client through their abstract interface to manipulate the instance, the product's specific class name is also separated from the implementation of the specific factory, does not appear in the client code.
Disadvantage: If you need to add a product, you need to increase the abstract class and the specific subclass of product, and need to modify the factory class code, which violates the open closure principle, the client will also appear the specific factory code, can be reflected + simple factory + configuration file to improve the way.

16. State mode
Definition: When an object's internal state changes to allow its behavior to change, the object looks like it has changed its class.

Thoughts: The state mode mainly solves the situation when the conditional expression that controls an object state transition is too complex. It is possible to simplify the complex judgment logic by transferring the judgment logic of the state to a series of classes representing different states.
Advantage: It will localize the behavior associated with a particular state and separate the behavior of the different states. That is, the specific state-related behavior is put into an object, because all the state-related code is channeling in a concretestate, so by defining a new subclass can easily add new states and transformations, the purpose is to eliminate the large conditional branch statements. By distributing the various state transfer logic to the sub-classes of states, the dependencies between them are reduced.
Usage Scenario: When an object's behavior depends on its state, and it must change its behavior based on state at run time, consider using state mode.

17. Adapter Mode
Definition: Transforms the interface of a class into another interface that the customer wants. The Adapter mode makes it possible for those classes that cannot work together because the interface is incompatible

Feeling: When the system data and behavior are correct, but the interface does not match, we should consider the adapter, the purpose is to make an existing object outside the control range to match an interface. The adapter pattern is primarily used in situations where you want to reuse some existing classes, but the interfaces are inconsistent with the reuse environment requirements.

Thoughts on design pattern

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.