Relive design Patterns

Source: Internet
Author: User

Design patterns, and the "routines" in software design. Each pattern describes a recurring problem around us, and the core of the problem solution, so that you can use it again and again without having to do repetitive work. There are more than 20 design patterns, which make it easier and easier to reuse successful designs and architectures to improve the effectiveness of system maintenance. Closely related to the design pattern is the 6 design principles, then from these design principles to begin the design of the pattern of the journey to revisit it. (PS: Content is a little bit smaller)

One, 6 design mode 1, single responsibility principle
    • Core idea: there should be and only one reason to change the class
    • Problem Description: If there is a class Class1 complete the duties t1,t2, when the responsibility T1 or T2 changes need to be modified, it may affect the class of another responsibility to work properly.
    • Benefits: reduced complexity of classes, improved readability, improved maintainability, increased scalability, and reduced risk of changes.
    • It is important to note that the single responsibility principle presents a standard for programming, with "responsibility" or "reason for change" to measure whether an interface or class is well designed, but "responsibility" and "reason for change" are not measurable, depending on the project and the environment.

A single responsibility is to let the class (or method) of the function of a single, so that the industry has and specialization, is not a bit of the sense of Unix design ideas?

2. Reese's replacement principle
    • Core idea: the subclass can be arbitrarily used where the base class is used, which guarantees that the subclass is perfectly substituted for the base class.
    • In layman's terms: as long as the parent class can appear where the subclass can appear. Conversely, the parent class may not be competent.
    • benefit: Enhance the robustness of the program, even if the child class is added, the original subclass can continue to run.
    • It is important to note that if a subclass does not fully implement the methods of the parent class, or if some methods of the parent class have "distorted" in the subclass, it is recommended that the parent-child inheritance relationship be broken by dependency, aggregation, composition, and so on instead of inheritance.
3. Dependency Inversion principle
    • The core idea : The high-level module should not rely on the underlying module, both should rely on its abstraction; abstraction should not depend on detail; Details should depend on abstraction;
    • Description : The high-level module is the call end, the lower layer module is the concrete implementation class. Abstraction refers to an interface or abstract class. The details are the implementation classes.
    • In layman's terms: the essence of dependency inversion is that by abstracting (interfaces or abstract classes) the implementations of each type or module are independent of each other, and the loose coupling between modules is realized.
    • Problem Description: Class A directly depends on class B, if you want to change class A to rely on Class C, you must modify the code of Class A to achieve. In this scenario, Class A is typically a high-level module that is responsible for complex business logic, and Class B and Class C are low-layer modules that are responsible for basic atomic operations, and if Class A is modified, it poses unnecessary risks to the program.
    • Solution: Modify Class A to dependency interface interface, Class B and Class C each implement interface interface, Class A through the interface interface indirectly with Class B or Class C, it will greatly reduce the chance to modify Class A.
    • Benefits : The benefits of dependency inversion are difficult to reflect in small projects. However, in large and medium-sized projects you can reduce the workload caused by changes in demand. Make parallel development more friendly.
4. Interface Isolation principle
    • Core idea : dependencies between classes should be based on the smallest interfaces
    • Generally speaking: to establish a single interface, do not build a huge bloated interface, as far as possible to refine the interface, the interface of the method as little as possible. That is, instead of trying to create a very large interface for all classes that depend on it, we need to create a dedicated interface for each class.
    • Problem Description: Class A through the interface interface dependency Class B, Class C through the interface interface dependency Class D, if the interface interface for Class A and Class B is not the minimum interface, then Class B and Class D must implement the methods they do not need.
    • Be aware that:
      • the interface is as small as possible, but there are limits . The refinement of the interface can improve the programming flexibility, but if it is too small, it will cause too many interfaces and complicate the design. So be sure to moderate
      • increase cohesion and reduce external interaction . Enable the interface to do the most things with the least amount of method
      • Customizing services for interfaces-dependent classes . Only exposes the calling class to the method it needs, and the method it does not need is hidden. A minimal dependency can be established only by focusing on providing a customized service for a module.
5. Dimitri Principle
    • Core idea: decoupling between classes.
    • In layman's terms: A class knows as little as possible about the classes it relies on. Since we began to touch programming, we have learned the general principles of software programming: low-coupling, high cohesion. Whether it is process-oriented programming or object-oriented programming, it is possible to increase the code reuse rate by minimizing the coupling between the modules. The advantages of low coupling are self-evident, but how do you program to do low-coupling? That's exactly what the Dimitri law is going to do.
6. Opening and closing principle
    • The core idea: try to expand the software entity to address the change in demand, rather than modify the existing code to complete the change
    • Generally speaking: a software PRODUCT in the life cycle, will change, since change is an established fact, we should be designed to adapt to these changes, to improve the stability and flexibility of the project.
Summary of Design principles

The principle of single responsibility tells us that the realization of the class to be a single duty; the Richter substitution principle tells us not to destroy the inheritance system; The dependency inversion principle tells us to interface-oriented programming; The interface isolation principle tells us to streamline the single interface when designing interfaces, and the Dimitri Law tells us to reduce coupling. And the open and closed principle is the master, he tells us to be opened on the extension, close to the modification.

Two, 23 design patterns------------------------------The creation mode------------------------------1, single-case mode

The singleton mode ensures that a class has only one instance, initializes it itself and provides it to the entire system. Only one instance of a class reduces memory overhead, especially when an object is frequently created for destruction. The singleton pattern can be subdivided into 2 modes, a hungry man and lazy, the difference is that the time of initializing the instance is different, the former is initialized on the definition, the latter is initialized on the first use, and the concurrent access of multi-threads is noticed here.

>> Singleton pattern Sample code <<

2, factory method mode

the meaning of the factory method mode is to define a factory interface that creates the product object and defer the actual creation to the subclass Factory. The Core factory class is no longer responsible for product creation, so that the core class becomes an abstract factory role and is responsible only for the interfaces that a specific factory subclass must implement, and the benefit of further abstraction is that the factory method pattern allows the system to introduce new products without modifying the specific factory roles.

>> Factory Method Sample code <<

3. Abstract Factory mode

Providing an interface for creating a set of related or interdependent objects, and without specifying their specific classes, can be understood as an upgraded version of the factory method.

>> Abstract Factory Sample code <<

4. Builder mode

The builder pattern is also called the generator pattern, separating the construction of a complex object from its representation so that the same build process can create different representations. For example, a user class attribute has name, age, address, email, job ... And so on, if you want to create a user object, passing in all the properties is a bit too long, then you can use the builder mode, passing in a parameter to set the value of the corresponding property.

>> Builder Pattern Sample code <<

5. Prototype mode

The prototype pattern is defined as specifying the kind of objects created with the prototype instance and creating new objects by copying the prototypes. The core of the prototype pattern is a clone () method, in which the object is copied, and Java provides a cloneable to indicate that the object is replicable, and why is it called "marking"? This interface is only a marker, and it is possible to copy objects with this tag in the JVM. How do you get from "potentially copied" to "can be copied"? The way is to overwrite the clone () method .

>> prototype Mode <<

-------------------------------Structured Mode------------------------------6, adapter mode

Adapter Pattern Definition: Transforms the interface of one class into another interface that the client expects, so that two classes that would otherwise not work together because of an interface mismatch can work together.

Considerations for Adapter Mode

Adapter mode It is best not to consider it in the detailed design phase, it is not to solve the problem that is still in the development phase, but to solve the project problem that is in service, no system analyst will consider using the adapter mode when doing the detailed design, this pattern uses the main scene is the extension application, As with the example above, the system expands to consider reducing the risk of code modification through adapter mode when it does not conform to the original design.

>> Adapter Pattern Sample Code <<

7. Decoration mode

Dynamically adding additional responsibilities to an object, the adornment pattern is more flexible than generating subclasses in terms of added functionality. The adornment mode is equivalent to adding a package class to the outer layer of a build class.

>> decoration Mode Sample code <<

8. Agent Mode

Proxy mode is a very high-usage pattern that provides a proxy for other objects to control access to this object.

In Java, there is a dynamic agent technology, dynamic Proxy refers to the implementation phase does not care who the agent, and in the run phase to specify which object.

>> proxy mode Sample code <<

9. Combination Mode

Combined mode combines objects into a tree structure to represent a "whole-part" hierarchy, which makes the user consistent with the use of individual objects and composite objects.

    • Component Abstract Component roles: Define common methods and properties for participating in composite objects, define some default behaviors or properties, such as the getinfo in our example are encapsulated in an abstract class.
    • Leaf leaf component: A leaf object with no other branches under it, that is, the smallest unit of traversal.
    • Composite Branch Component: The Branch object, which functions as a tree-shaped structure composed of a branch node and a leaf node.

>> combination Mode Sample code <<

10. Façade mode

The façade mode requires that the outside of a subsystem and its internal communication be carried out through a unified object. Façade mode provides a high-level interface that makes subsystems easier to use.

    • Facade Façade role: The client can invoke the method of this role. This role knows all the functions and responsibilities of the subsystem. In general, this role delegates all requests from the client to the appropriate subsystem, saying that the role has no actual business logic, just a delegate class.
    • SUBSYSTEM subsystem role: You can have one or more subsystems at the same time. Each subsystem is not a separate class, but a collection of classes. The subsystem does not know the presence of the façade. For subsystems, the façade is just another client.

>> façade mode sample code <<

11. Enjoy meta mode

Enjoy meta-mode is an important implementation of pool technology, using shared objects can effectively support a large number of fine-grained objects.

>> enjoy meta-mode sample code <<

12. Bridging mode

Bridge pattern Definition: decoupling abstractions and implementations so that they can change independently.

    • Abstraction -Abstract Role : Its primary responsibility is to define the behavior of the role, while preserving a reference to the implementation role, which is generally an abstract class.
    • implementor -Implementation Role : It is an interface or abstract class that defines the required behavior and properties of a role.
    • refinedabstraction --Fix the abstract role: it refers to the implementation of the role to modify the abstract role.
    • Concreteimplementor --Implement a specific role : it implements the methods and properties defined by an interface or abstract class.

>> Bridging Mode Sample code <<

------------------------------behavior Pattern------------------------------13, responsibility chain mode

Responsibility chain pattern Definition: Enables multiple objects to have the opportunity to process requests, thus avoiding the coupling between the sender and receiver of the request. Make a chain of these objects and pass the request along the chain until an object has processed it.

>> Responsibility chain Model sample code <<

14. Iterator Mode

The iterator pattern provides a way to access individual elements in a container object without exposing the object's internal details (which is rarely used, and the container typically provides iterators).

>> iterator Pattern Sample code <<

15. Intermediary mode

Encapsulates a series of object interactions with a mediation object, which allows the objects to interact with each other without displaying the interaction between them, thus allowing them to be loosely coupled and independently changing their interactions.

The advantages of the Terminator pattern : To reduce the dependency between the classes, the original one-to-many dependencies into a single-dependency, peer-class only rely on intermediaries, less dependence, reducing the coupling between classes.

The disadvantage of the Terminator pattern : The Terminator will swell up very large, and the logic is very complex, the original N objects directly from the interdependence of the transition to the mediator and colleague class dependency, the more colleague class, the more complex the logic of the intermediary.

>> intermediary mode design pattern <<

16. Template Method

Defines a framework for an algorithm in an operation, and delays some steps into subclasses. Enables subclasses to redefine some specific steps of the algorithm without changing an algorithm.

Basic Method : Also known as the basic operation, is a method implemented by the subclass, and is called in the template method

Template Method : can have one or several, is generally a concrete method, that is, a framework to implement the basic method of scheduling, complete the fixed logic. The template method is generally added to the final keyword, which does not allow overwriting

>> Template Method Sample code <<

17. State mode

State pattern Definition: When an object's internal state changes to allow it to change its behavior, the object looks like it has changed its class. The core of the state pattern is encapsulation, and the change in state causes the behavior to change, from the outside it looks as if the corresponding class of the object has changed.

state--Abstract State role

Interface or abstract class that is responsible for the object state definition and encapsulates the environment role for state switching.

concretestate--Specific Status roles

Each specific state must complete two duties: The behavior management of this state and the tendency to deal with the state, in layman's terms, is what to do in this state, and how this state transitions to other states.

context--Environmental Role

Defines the interfaces required by the client and is responsible for the switchover of the specific state.

>> status Mode sample code <<

18. Strategy Mode

The policy pattern is a relatively simple pattern, defining a set of algorithms that encapsulate each algorithm and make them interchangeable.

>> Policy Pattern Sample code <<

19. Memo Mode

Memo pattern Definition: captures the internal state of an object without destroying the encapsulation, and saves the state outside the object. The object can then be restored to its previously saved state.

>> Memo Pattern Sample Code <<

20. Observer mode

The Observer pattern (Observer pattern) is also called the Publish-subscribe pattern, which is defined as follows: Defines a one-to-many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and updated automatically.

>> Observer Pattern Sample code <<

21. Visitor Mode

Encapsulates operations that act on elements of a data structure, and it can define new operations that act on these elements without altering the data structure.

>> Visitor Pattern Sample code <<

22. Command mode

The command pattern is a high-cohesion pattern, defined as the ability to encapsulate a request as an object, allowing you to parameterize the client with different requests, arrange or log requests, and provide undo and redo of the command.

>> command Pattern Sample code <<

23. Interpreter Mode

The interpreter pattern definition: Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.

Reference:

1, "Zen of Design Pattern"

2. "Design mode-the basis of reusable object-facing software"

3, Https://github.com/luoxn28/ThinkInTechnology/tree/master/DesignPattern

Relive design Patterns

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.