preface

The personal summary front end contains self-summaries, as well as original instances. Personally feel more easy to understand, suitable for beginners quick entry. Welcome to follow.

This article includes the understanding of design patterns, basic principles of design patterns, classification of design patterns, and common design patterns application examples.

All are personal original summary, if there is any wrong, hope to point out.

In this article

topic source
What are design patterns Personal understanding
Basic guidelines for design patterns Personal understanding + Reference link:www.jianshu.com/p/62b69282b…
Classification of design patterns Personal understanding + Reference link:www.jianshu.com/p/eafc4ca17…
Design pattern application examples Personal understanding, including basic understanding, business scenarios, code scenarios, pros and cons, and some code examples
The article conclusion Personal understanding, unavoidable error, welcome message correction

What are the design patterns for the front end

Generally speaking, it is a kind of inertia thinking of daily use design. Because this kind of thinking has specific advantages for specific business or code scenarios, it becomes a "design pattern" in the industry.Copy the code

Basic guidelines for front-end design patterns

Code optimization Step 1: The single responsibility principle makes the program more stable and flexible: The Open and Close Principle Builds a system that is more scalable: The Li Substitution principle gives the project the ability to change: The Dependency inversion principle Systems have more flexibility: The interface isolation Principle Better scalability: the Demeter PrincipleCopy the code

Types of design patterns

1. Create the schema
Generally used to create objects. Including: singleton pattern, factory method pattern, abstract factory pattern, Builder pattern, prototype pattern.Copy the code
2. Structural mode
The emphasis is on the "inheritance" relationship, with a layer of inheritance, and generally with the "agent". Includes: adapter mode, bridge mode, composite mode, decorator mode, appearance mode, share mode, proxy mode, filter modeCopy the code
3. Behavioral patterns
Division of responsibilities, separate, reduce external interference. Includes: command pattern, interpreter pattern, iterator pattern, mediator pattern, memo pattern, observer pattern, state pattern, policy pattern, template method pattern, visitor pattern, responsibility chain patternCopy the code

Examples of common front-end design patterns:

1. Singleton mode
Basic Understanding: Does an "instance" that is likely to be repeated cost performance if it is created repeatedly? If you take the first instance and then just reuse it, you achieve your goal of saving performance. Service scenario: A pop-up dialog box is displayed after login. If the pop-up box is cancelled, the original pop-up box is displayed instead of being created again. Var myLogin = function(fn){var result; Return the function () {return result | | (result = '< div > I am a login box < / div >'); }}Copy the code
2. Simple Factory mode
Basic understanding: The simple factory pattern is called the static factory method pattern, and a factory object determines which instance of a product class to create. Business scenario: Foxconn needs to produce huawei, Apple and other mobile phones at the same time. We can use a factory model. As long as the manufacturer inputs the model, the corresponding mobile phone can be produced. Disadvantages: 1) If you add a new type, you need to modify the factory, which violates the open closed principle (ASD) 2) It is not suitable to use related code when there are too many subclasses or too many subclass levels:  function CreatPhone( type ) { retrun new AbstractPhoneFactory( type ); } class AbstractPhoneFactory(){ constructor(options){ this.phone = null; swicth options.type: case "huawei": this.phone = new HuaweiFactory(); break; case "apple": this.phone = new AppleFactory(); break; } retrun this.phone; } } class HuaweiFactory(){ constructor(){ } } class AppleFactory(){ }Copy the code
3. Abstract factory pattern
Basic understanding: More abstract objects than simple factories. Abstract factories are at the heart of the factory method pattern, and all factory classes that create objects must implement this interface. Advantages: Users can obtain the corresponding class instance according to the parameters, avoiding the direct instantiation of the class and reducing the coupling. Disadvantages: 1) If a new type is added, the factory needs to be modified, which violates the open closed principle (ASD). 2) It is not suitable for business scenarios when there are too many subclasses or too many subclasses: as above, if the phone color, memory size is also required.Copy the code
4. Builder mode
Basic understanding: Use multiple simple objects to build a complex object step by step. It may have more complex objects to create than factory mode. Advantages: 1, independent builder, easy to expand. 2, easy to control the details of risk. Disadvantages: 1, the product must have something in common, the scope is limited. 2. If the internal changes are complex, there will be many construction classes. Business scenario: when you go to KFC, hamburger, Coke, French fries, fried chicken wings and so on remain the same, while their combination changes frequently, resulting in the so-called "set meal".Copy the code
5. Prototyping
Basic understanding: This is the prototype pattern when you want to generate objects by cloning or copying them. Advantages: 1. Improved performance. 2. Avoid constructor constraints. Disadvantages: 1, performance improvement. 2. Avoid constructor constraints. Business scenario: Constructors generate entitiesCopy the code
6. Adapter mode
Basic understanding: Make two previously incompatible interfaces work together. Can be divided into: adapter, object adapter and interface adapter optimization: reuse, the reuse of existing classes, solves the inconsistency of classes and reuse existing environment or low coupling: the need to modify the original code, follow the principle of open and close) disadvantages: too much use of the adapter, your program does seem more complex business scenarios: When your computer only supports USB plugs and the mouse is PS/2, you need a PS/2 and USB adapter to connect. Code scenario: native Android Adapter adapter,json format data unificationCopy the code
7. Bridge mode
Basic understanding: multi-dimensional separation of its abstract parts, making each dimension independent. We then "cross" the bridge to get the result we want. Advantages: 1. Separation of abstract interface and its implementation. Improved solutions that are better than inheritance. 2. The bridge mode improves the scalability of the system. It does not need to modify the original system to expand any one of the two change dimensions. 3. Implementation details are transparent to customers, and implementation details can be hidden to users. Disadvantages: 1. The introduction of bridge mode will increase the difficulty of understanding and designing the system. Since the aggregation association relationship is established at the abstraction layer, developers are required to design and program for abstraction. 2. Bridge mode requires the correct identification of two independent changing dimensions in the system, so its application scope has certain limitations. Business scenario: When using a screenshot mark, do I choose a color and then a shape? And then bridge it to an object. This is the bridge mode.Copy the code
8. Combination mode
Basic understanding: Emphasize the "parts-whole" hierarchy. The composite pattern enables users to manipulate both individual and composite objects in a consistent way. Separable: combined relationship, aggregation relationship advantage: no relationship processing of a single object, or combined object container, to achieve decoupling between containers. It is easy to add new parts when they are available. Disadvantages: Clients need to spend more time sorting out the hierarchical relationships between classes. Business scenario: Composite relationships: Multiple programmers, managed by a CTO. Aggregation: a teacher has many students, but each student belongs to multiple teachers.Copy the code
9. Decorator mode
The Decorator Pattern allows you to add new functionality to an existing object without changing its structure. Advantages: Decorator and decorator classes can develop independently and are not coupled to each other. Disadvantages: multi-layer decoration will appear complex. Business example: The relationship between a frame and a photo. React high-order components (e.g. all components with a border)Copy the code
10. Appearance mode
Basic understanding: Hide complex relationships. The facade pattern defines a high-level interface that makes this subsystem easier to use. Advantages: 1. Reduce system interdependence. 2. Increase flexibility. 3. Improved security. Disadvantages: inconsistent with the principle of open and close, if you want to change things is very troublesome, inheritance rewrite are not appropriate. Business example: when going to the hospital to register, the registration hall is the "appearance", which may contain complex medical relations, but we only need to "simple" registration through the "registration desk". Code example: Component libraryCopy the code
11. Enjoy yuan mode
Basic understanding: can be understood as a pool technology, String constant pool, database connection pool, buffer pool, etc., there are a large number of objects, need to alleviate the time. Performance optimization mode. Advantages: Greatly reduce object creation, reduce system memory, improve efficiency. Disadvantages: The complexity of the system is increased, and the external state needs to be separated from the internal state, and the external state has the nature of inherent, should not change with the change of the internal state, otherwise it will cause the chaos of the system. Case study: Assume that same-day sales have not been aggregated for the last ten years. At this point, there is a function to query the day's sales statistics by date. We can query the date, save the value, the next query we directly get the value. Code: String constant pool, database connection pool, buffer pool, etcCopy the code
Filter mode
Basic understanding: Let developers filter a set of objects using different criteria. Advantages: Can quickly obtain the required object. Cons: Iterate over all data. Case study: Select a group of married men.Copy the code
13. Proxy mode
Basic understanding: A class represents the functionality of another class. We create objects with existing objects to provide functional interfaces to the outside world. Advantages: 1. Clear responsibilities. 2. High scalability. Disadvantages: 1. Some types of proxy modes may slow down the processing of requests due to the addition of proxy objects between the client and the real subject. 2. Implementing the proxy pattern requires additional work, and some of the proxy pattern implementations are quite complex. Application example: 1. Shortcuts in Windows. Note the following differences: adapter mode mainly changes the interface of the object considered, while proxy mode does not change the interface of the proxied class. 2. The difference between decorator mode and decorator mode: Decorator mode is for enhancement, while proxy mode is for control.Copy the code
14. Command mode
Basic understanding: A request is wrapped in an object as a command and passed to the calling object. Advantages: 1, reduce the coupling degree of the system. 2. New commands can be easily added to the system. Disadvantages: Using command mode can cause some systems to have too many specific command classes. Life example: Remote control, control TV, is a command mode. Practical case: 1. We Npm start the project command, is also a command mode. 2. Applets service notification, by the server to initiate a command, is also a command mode.Copy the code
15. The intermediary model
Basic understanding: provides a mediation class that typically handles communication between different classes. Advantages: 1. Reduces the class complexity and transforms one-to-many into one-to-one. 2. Decoupling between classes. Disadvantages: When intermediaries are large, they become complex and difficult to maintain. Application example: 1. Chat room for users to chat, chat room is an intermediary 2. Real estate agent combat case: traditional front-end MVC model. C can be understood as the intermediary between M and V. vuex.Copy the code
16. Memo mode
Basic Understanding: Advantages: Provides a mechanism for users to recover the state, so that users can easily return to a historical state. Disadvantages: consumption of resources, there is a certain memory consumption. Application example: the browser page mechanism, can be rolled back. Actual combat case: database transaction management, can be rolled back.Copy the code
17. Observer (publish subscribe) mode
Basic understanding: namely publish, subscribe process. Defines a one-to-many dependency between objects, notifies corresponding properties when objects change. The publish-subscribe pattern belongs to the observer pattern in a broad sense. Observer mode: The Observer directly subscribes to a Subject, and when the Subject is activated, it fires events within the Observer. Publish and subscribe model: Subscriber registers the event they want to Subscribe to the dispatch center. When Publisher publishes the event to the dispatch center, that is, when the event is triggered, The processing code registered with the dispatch center by the Fire Event subscriber. Advantages: 1. The observer and the observed are abstractly coupled. 2. Build a trigger mechanism. Disadvantages: 1, too much consumption of energy. If there is a callback loop, the system will crash. 3. Business scenario: DOM click event listener. Code scenario: Use of EventEmitCopy the code
18. State mode
Basic Understanding: The behavior of a class changes based on its state. Advantages: 1. Encapsulate conversion rules. 2. Encapsulate states as enumerations to see all states at a glance. 3. Multiple environment objects can share a state object, thus reducing the number of objects in the system. Disadvantages: 1. The use of state mode will inevitably increase the number of system classes and objects. 2. The structure and implementation of state mode are complicated, which will lead to confusion of program structure and code if improperly used. 3. State mode does not support the "on/off principle" very well. Business scenario: When it's cold, we wear thick clothes. When it's hot, we wear short sleeves and that's a state behavior pattern. Note: Use state mode when behavior is constrained by state, and there are no more than five states.Copy the code
19. Strategic mode
Basic understanding: Give different algorithms or results for different time states. Advantages: 1. The algorithm can be switched freely. 2. Avoid using multiple conditional judgments. 3. Good expansibility. Disadvantages: 1. Policy classes will increase. 2. All policy classes need to be exposed. What we can do on weekdays and what we can do on non-weekdays. Year-end bonus will be paid according to employee's performance. Code scenario: Form represents validation. Special note: If there are more than four strategies, consider a hybrid mode.Copy the code
20. Interpreter mode
Basic Understanding: Define an interpreter when an "action" needs to be interpreted one particular context at a time, thousands of times. Advantages: 1. Good scalability and flexibility. 2. Added new ways to interpret expressions. 3. Easy to implement simple grammar. Disadvantages: Less available scenarios. 2. It is difficult to maintain complex grammar. Interpreter schema causes class bloat. Actual combat case: SQL printerCopy the code
21. Template mode
Basic understanding: But calls will be made in the way defined in the abstract class. This type of design pattern is behavioral. Advantages: 1. Encapsulate the invariant part and expand the variable part. 2. Extract common code for easy maintenance. 3. The behavior is controlled by the parent class and implemented by the subclass. Disadvantages: Each different implementation requires a subclass to implement, resulting in an increase in the number of classes, making the system larger. Application example: jPA method encapsulation. Vue official API code example: Vue solt methodCopy the code
22. Visitor pattern
Basic understanding: Separating data structures from data operations.Copy the code
23. Iterator pattern
Basic understanding: Provides a way to access the elements of an aggregate object sequentially without exposing the object's internal representation. Advantages: The iterator pattern controls the order in which data is accessed from outside the container. It allows you to traverse an aggregate object in different ways. Disadvantages: added complexity to the system. Example: Iterable implements each mapCopy the code
23. Chain of responsibility model
Basic understanding: A chain of execution used to handle related transaction responsibilities. Advantages: 1, reduce the coupling degree. It decouples the sender and receiver of the request. 2. Simplifying objects. The object does not need to know the structure of the chain. 3. Increase flexibility in assigning responsibilities to objects. Responsibilities can be dynamically added or removed by changing members in the chain or reordering them. 4. Adding new request handling classes is convenient. Disadvantages: There is no guarantee that the request will be received. Code debugging is not convenient and may cause loop calls to application instances: KOA source code. Events bubble in JSCopy the code