TOC needs to have a basic look at design patterns, combined with beginner tutorials and so on

One, twenty-three design modes

With the development of the Internet industry, the design model is not much change, expansion. Here are 23 common design patterns!!

1.1 Factory method pattern

The common behavior of multiple code sections is abstracted into interfaces to define, and the concrete implementation is defined after the subclass implements the parent class. Finally, a factory class is used to select and return the corresponding instantiated object based on the passed parameter. Keyword: Factory class generally with Factory

1.2 Abstract factory pattern

Abstract factory is an abstract class of other factory classes, that is, AbstractXXX abstract factory class is extracted from the common behavior of other factory classes. In abstract factory mode, another implementation of abstract factory is used, including agents, adapters and abstract factories. The two cache-mode implementations of CacheService are added with adapters that correspond to the methods of the CacheService interface, and then dynamic proxies are used, where the method calls are encoded to the invoke method of the invocation handler when the proxy instance calls the method. You can think of the adapter classes for different caching patterns as building classes for factories that have common getters and setters. These common behaviors are abstracted into CacheService, where methods called in service actually call methods in the adapter class through dynamic proxies.

        CacheService proxy_EGM = JDKProxy.getProxy(CacheServiceImpl.class, new EGMCacheAdapter());
        proxy_EGM.set("user_name_01".Little Fuge.);
        String val01 = proxy_EGM.get("user_name_01");
        System.out.println("Test Results:" + val01);
        
	    CacheService proxy_IIR = JDKProxy.getProxy(CacheServiceImpl.class, new IIRCacheAdapter());
        proxy_IIR.set("user_name_01".Little Fuge.);
        String val02 = proxy_IIR.get("user_name_01");
        System.out.println("Test Results:" + val02);
Copy the code

1.3 Builder mode

In daily life, decorating house would be based on different scenarios, brand, model, price and so on combination formed A variety of decorate A style, set A: contemporary and contracted, plan B: light luxury pastoral, package C: european-style luxury) will not change some basic material, and the combination of often change over time, you can choose the builder pattern to build the code. Builder

1.4 Prototype Mode

In the exam, each examinee gets roughly the same exam paper topic, are from the same exam question pool random combination of a set of questions out and distributed to all examinees for the exam, but the questions, the same topic order, easy to cause cheating, and still constantly create initialization unified object. Use prototype patterns: Create complex objects by cloning, avoid repeated initialization operations, and do not need to be coupled to other classes that belong to the class. However, there are some disadvantages that can make this pattern extremely cumbersome if the objects include clones of circular references, as well as clones of deeply used objects in the class. Cloneable is implemented (out of order in overridden clone methods)

1.5 Singleton Mode

Get the same instance each time you get or create. For example: Spring’s @autowird automatic injection of objects is also a representation of the singleton pattern. The underlying singleton pattern is determined by the Bean injection pattern. The singleton pattern is to put the instance created by new into the container, and get the instance object every time. NewInstance proposes to use the enumerated singleton pattern to solve the most important problem; Thread-safe, free serialization, single instance. enum

1.6 Adapter Mode

Create an adapter interface for classes that have common behavior but call different methods. The implementation class of the adapter actually calls the corresponding methods of the original object. The interface has been uniformly wrapped so that external use does not need to care about the internal logic. And in the call only need to pass unified parameters, so that meet the role of adaptation. Adapter

1.7 Bridge Mode

The main role of the bridge pattern is to combine multiple matching uses by separating the abstract from the implementation. To put it bluntly, the core implementation is A class A with A class B interface, passing the implementation of class B through constructors, and that class B is the bridge of the design. Through the simulation of wechat and Alipay in different payment modes, the combination of face brush, fingerprint and password reflects the reasonable application of bridge mode in such scenarios. ZfbPay = new zfbPay (new PayFingerprintMode()); Bridge/ passes in other objects at initialization as a judgment of the class’s execution method

1.8 Combination mode (no fine products)

The main solution of the composite pattern is a series of simple logical nodes or extended complex logical nodes under different structure organization, for external calls can still be very simple.

1.9 Decorative mode (no fine items)

new BufferedReader(new FileReader(“”)); , this code you are familiar with, I believe that learning Java development to byte stream, character stream, file stream content have seen such code, a layer nested a layer, a layer nested a layer, byte flow character stream and so on, and the use of this way is a manifestation of the decorator mode.

1.10 Appearance mode (no fine products)

The facade pattern, also known as the facade pattern, is designed to reduce the complexity of the logical combination of interfaces used by callers. This provides an intermediate layer between the caller and the actual interface provider, which provides the API interface for the wrapping logic. Sometimes the facade pattern is also used in the middleware layer to wrap the generic complex logic in the service so that the consumer can only care about business development.

1.11 Free Yuan mode

The share mode is used to share common objects, reducing memory usage and improving system access efficiency. These shared objects usually consume memory or need to query a large number of interfaces or use database resources, so they are all removed and used as shared objects. Through a variety of ways to reuse the data cache the entire object, reduce memory footprint and the number of queries Seconds kill under the scenario of the activity, activity information is not the same, only the goods inventory in the event of a transformation, every time information from a database access to the activities of the object in addition to the inventory information is consistent with the other, this time can use the flyweight pattern, The repeated parts are cached for repeated use. Here, the element factory is used, the active information is cached from the database with map during initialization, and the inventory information is later fetched from redis and spliced into the active information.

1.12 Agent Mode (no details)

The agency model is a bit like the boss and the little brother, and a bit like the distributor. The main solution is to provide convenient proxy services for access to some resources and easy operation of object classes. This pattern of design thinking is often found in our systems, or in the components you use, which give you a very simple and easy way to control the service classes that you would otherwise have to write a lot of code to use. Basically: a series of encapsulation designs after the implementation of the proxy. We adopt the development of a part of the core functions of Mybatis – Spring middleware to reflect the power of the proxy mode, so it involves some knowledge points about the creation of proxy classes and the registration of beans in Spring, which may be rarely used in ordinary business development. But it is a very common operation in middleware development. In addition to developing middleware, proxy mode can also be the packaging of services, Internet of Things components and so on, making complex services into lightweight invocation and cache use. You can understand it as the light switch in your home. We cannot operate the human flesh connection of 220V wire, but we can use the switch to avoid electric shock. The design of proxy mode can make the code more clean, clean and easy to maintain. Although many additional classes are added in this part of the development, including the registration of their own processing beans, etc., such middleware is highly reusable and more intelligent, which can be easily extended to various service applications.

1.13 chain of responsibility

I am familiar with this, more commonly used and relatively simple one, the core of the responsibility chain model is to solve a group of services in the execution of the processing relationship, a bit like you have no money to spend, the need for family financial expenditure approval, less than 10 yuan to find daughter approval, 100 yuan first daughter approval in daughter-in-law approval. You can imagine that when you want to change jobs you are arranged to be signed off on by the various leaders.

Chain of Responsibility model1.The core idea is chain execution, and the execution of each node depends on the execution result of the node at the next level.2.Abstract parent class: Action Property: Action Action is used to store the object pointing to the next node reference abstract method: start() The implementation of the subclass to define the current node specific logic implementation method: Action () node to execute the decision branch, success-enter the next nodedoReturn subclass: openDeviceAction (multiple subclass nodes, etc.) Override the start () method to implement the concrete logical assembly execution class: Call (encapsulate the sequence of execution actions, logic, and where needed) creates the required node, uses setNext to specify the next node (execution order), and calls the action () of the first node to start3.Key words linked list data structure, the essence of responsibility chain is a linked list data structure, through the Node points to the Next Node to ensure the execution order of the Node, (Next, Node)Copy the code

1.14 Command Mode

The core logic of the command scene is that the caller does not need to care about the implementation of specific logic. In this scene, the ordering personnel only need to hand over the various cuisines to the second cook, and then the second cook gives the dishes to each chef for cooking. That is, the ordering personnel do not need to communicate with various chefs, only need to give orders in a unified environment. In fact, my understanding is that this pattern is a kind of behavior encapsulation, the next time you want to use this part of the code directly call method, rather than writing a long series of code. The feature here is that the called party and the behavior are abstracted to the interface, in which the caller can use the polymorphic call to use the concrete implementation of the called party and the behavior method command mode use scenario needs to be divided into three relatively large blocks; Command, implementation, caller, and the separation of these three pieces of content is also a key factor in the selection of suitable scenarios, through such separation can make logic have the nature of a single responsibility, easy to expand.

1.15 Iterator mode (no details)

The iterator pattern is the iterator we use every day. Although this design pattern is rarely seen in our actual business development scenarios, it is traversed almost daily using the List collection provided by the JDK. The enhanced for loop is a loop that outputs data, but it is not an iterator pattern. Iterator mode is characterized by the implementation of the Iterable interface, through the way of next to get collection elements, and at the same time with the element deletion operations. Enhanced for loops are not. In addition, elements are not allowed to be deleted during iteration. The advantage of this design pattern is that it allows us to iterate over different data structure elements in the same way. Array, linked list, tree, etc., while users do not need to care about the traversal processing logic of each kind of data structure when using traversal, so that the use becomes unified and easy to use.

1.16 Intermediary Mode (no details)

The intermediary mode is to solve the repeated calls between complex functional applications, adding a layer of intermediary packaging services in this middle, to provide simple, universal and easily extensible service capabilities. Such a design pattern can be almost seen in our daily life and practical business development, for example; The plane 🛬 lands with a little sister Shouting at the tower, waiting for the train from any direction will get off and get off the platform, the company’s system has a center platform specifically for you to package all interfaces and provide unified services, and so on, all of which use the intermediary mode. In addition, some of the middleware you use encapsulates the underlying differentiation of multiple databases and provides a very simple way to use them. Personal understanding is to solve the problem of resource sequence scheduling in complex scenarios.

1.17 Memo Mode (no details)

The memo mode is a design mode with the core functions of recovery or rollback, configuration, version and resetting, and this design mode belongs to the behavior mode. On the basis of not destroying the original object, the memo operation class is added to realize the memo mode by recording the behavior of the original object. In my personal understanding, when an information is modified, the last message is recorded through the cache and storage table, and then rolled back to the required configuration information through the history record.

1.18 Observer mode

Simply speaking, the observer 🕵 mode means that when a behavior occurs, information is transmitted to another user for receiving and corresponding processing. There is no direct coupling between the two.

For example; Sniper, Li Yunlong. And many frameworks will have listeners, through annotations, when the listening mode is executed, it will also execute the corresponding listening method (listening database inventory changes, front-end statistics inventory changes, etc.). There is also the consumer pattern in MQ, again by listening for messages in queues and then consuming them, which is also the idea of the observer pattern, listening for actions, subscriptions

1.19 Status Mode

State model describes a behavior under various state changes, such as our one of the most common site of page, under the login and don’t you login show content is slightly different (not login cannot display personal information), and the login and login is by changing our state, and make the whole behavior has changed.At least some people born in the 1980s and 1990s have used a tape player. On the top of the tape player is a row of buttons. When you put the tape into the machine, you can use the buttons to tell the player to play the content on the tape. You can only press other buttons when you are in one state (this is also a key point in design mode). In different states, different pages are displayed and different data can be queried. If district-level units only look at the current area, city-level units can look at all areas and control them step by step according to the state, unit and the difference of a certain field.

1.20 Policy Mode

The policy pattern is also the most commonly used and simplest design pattern, and is often used to replace the choice scenario of multi-branch ifelse, if the business process has an indefinite future trend of scaling, otherwise it does not fit the usage scenario. For example, the current system needs to make a function to access the third-party payment, here we can use the strategy mode to create a specific implementation of branches of different payment methods, even if temporarily supported: Wechat, Alipay, wallet and other payment methods, but with the development of business volume and the surge of user groups, it is inevitable to expand to support unionPay payment and other scenarios. In this case, it is reasonable to use the strategic mode. Finally, the policy pattern is implemented by abstracting the behavior methods of multiple branches in an interface, the implementation of which is defined by subclasses. The policy pattern also requires a policy control class to invoke specific implementations using polymorphism based on incoming objects. Ifelse –> Policy interface, implementation class, policy control class (important: remember that the current business is extensible to choose to use, otherwise if just write dead two or three branches to use policy mode will increase memory consumption and management costs)

1.21 Template mode (no fineness)

The core design idea of the template pattern is to define the order of execution of abstract methods in an abstract class, and to make the abstract methods subclass only, but not to design independently accessible methods. Simply put, make your schedule very clear. The template pattern is very convenient in defining the uniform structure, namely the implementation standard, which is a good control of the subsequent implementers do not care about the call logic, according to the uniform way of execution. Then the inheritors of the class need only care about the concrete implementation of the business logic.

1.22 Visitor Mode (no details)

The core issue for visitors is to add volatile business access logic to a stable data structure, such as user information, employee information, and so on. A design pattern that decouples these two parts of the business to enhance scalability.

1.23 Interpreter mode

The Interpreter Pattern, which provides a way to evaluate the syntax or expressions of a language, is a behavioral Pattern. This pattern implements an expression interface that interprets a particular context. This pattern is used in SQL parsing, symbol processing engines, and so on. A bit like in a code generator, the {name} expression is replaced with a “three” interpretation of the actual queried data.

2. The nature of design patterns? What kind of problems do you want to solve?

The concept of design pattern was first proposed by Christopher Alexander in his book Architectural Pattern Language. This book introduces the "language" of urban design, providing 253 models for describing the construction of towns, neighborhoods, houses, gardens, rooms and the west. The basic unit of this "language" is pattern. Later, four authors - Erich Gamma, John Friesides, Ralph Johnson, and Richard Helm - embraced the concept of patterns. In 1994, they published Design Patterns: The Foundation of Reusable Object-oriented Software, which applied the concept of design patterns to the field of program development.Copy the code

There are a few people out there who haven’t read the books on design patterns and can still write great code. This is mainly due to the experience extracted from the years of programming process through the tempering of numerous projects and the continuous pursuit of programming. This lesson will ultimately be almost identical to the design pattern, which is highly cohesive, low coupled, scalable, and reusable. You’ve probably had the same experience learning the source code for a framework and finding that some of the design is the same as it was when you were developing. In fact, all design patterns are basically inseparable from some ideas transformed from experience: decoupling, cohesion, encapsulation (reuse), abstraction, polymorphism, etc. The use of design patterns will make the whole program organization level become clearer, the responsibility division between each class is more clear, the code reuse is stronger.

3. How not to abuse design patterns?

Combined with the actual business requirements, scenarios, future development direction, and possible demand changes. Then choose the use/combination as you see fit.Copy the code

4. The evolution of ideas

  • 1. Wow, this abstract design is really awesome!
  • 2. How do I wrap it?
  • 3. Who is the subject of these actions? What categories should I group them into?
  • 4. I can’t decide, which design pattern should I use?
  • 5. You can split this one up in a strategic mode.
  • 6. Leon? This amount of code also want to do? Difficult to manage, refuse!
  • 7. Back to nature, this business scene, can use this model, good good
  • 8. Huh? It would be more reasonable to use another pattern within this pattern, and the XXX pattern can be used for this requirement.
  • 9. Be in control and turn things upside down

Ii. Reference:

Little Fu Ge: bugstack.cn/itstack/its… Welcome to reprint, please indicate the source.

Update log

9-7

  • At the beginning, 23 core concepts of design patterns were briefly posted, which were further improved and supplemented

I’m Lin Xi, thank you so much for your support! Learn together and make progress together!