23 JavaScript Design Patterns

Source: Internet
Author: User
Tags class definition generator

original link:https://boostlog.io/@sonuton/23-javascript-design-patterns-5adb006847018500491f3f7f

Turn from:

https://mp.weixin.qq.com/s?__biz=MzUxMzcxMzE5Ng==&mid=2247488996&idx=1&sn= c337e4cfe2a67550f5f22536d58a9735&chksm= f951a0a7ce2629b13bb306f9a2410e2be8e9f6958756be40c36937371c4ff5dfef2b78bbbb19&mpshare=1&scene=23& Srcid=060272xasmjgvam6eohoezw7#rd

Author |sonuton

The translator-Hu Hongxing

Edit | Shanyun

1. Why should I learn design patterns?

In many interviews, you may encounter many interfaces in object-oriented programming, abstract classes, proxies, and other issues related to design patterns. Once you understand the design pattern, it will allow you to easily respond to any interview and apply these features to your project. Implementing design Patterns in the application has been validated and tested.

To make your application scalable, reliable, and maintainable, you should write code that conforms to design patterns.

2. What is design mode?
    • Design patterns are a reusable solution to the problems we experience in programming every day.

    • The design pattern is mainly to solve the problem of object generation and integration.

    • In other words, design patterns can be used as templates that can be applied to real-world programming problems.

3. Development history of design patterns

The concept of design patterns is presented by gang of four (four authors of the design pattern (reusable object-oriented Software Foundation)).

Gang of four the book into two parts:

    • The first part explains the advantages and disadvantages of object-oriented programming.

    • The second part is about the evolution of the 23 classic design patterns.

Gang of four design patterns play an important role in the software development life cycle since the design pattern concept is presented.

4. Design Pattern Classification

According to the different problems encountered in practical application, gang of four will divide the design pattern into three kinds.

    • Create pattern

    • Structural mode

    • Behavioral patterns

The next step is to outline the main concepts that fall into the 23 design patterns of these three types.

4.1 Create pattern

This type of pattern is used for object generation and life cycle management.

Creative mode can determine which objects are generated and increase the flexibility of the program. The pattern is as follows:

    • Abstract Factory mode

    • Generator mode

    • Factory method Mode

    • Single-Case mode

    • Prototype mode

4.1.1JavaScript Abstract Factory mode # What is the abstract factory model?

It's like a factory, but everything is packaged up:

    • Methods of providing objects

    • Factories that build objects

    • The final object

    • The final object contains objects that use the policy mode

The policy pattern is just a combination of ways, in other words, its class field is actually the object itself.

# What is the use of abstract factories?

Abstract Factory mode allows you to create objects of class cluster classes without specifying a specific class, which makes the abstract factory flexible.

Abstract Factory mode allows you to model any class cluster object and use it for external objects through a unified interface.

The only downside to an abstract factory is that it can become very complex.

4.1.2JavaScript Generator Mode (builder mode)What is #Builder mode?

The Builder pattern is a pattern for creating objects that are composed of other object combinations. The method that creates the part should be independent of the main object. In addition, to hide the creation details of a part from a business party, the two are independent of each other.

When using the generator pattern, the generator knows all the details and the creation details are completely masked against other related classes.

4.1.3JavaScript Factory Method mode# What is the factory method model?

By definition, you can use Factory mode whenever you want a method to return one of several possible classes of a public superclass.

Suppose I want to randomly shoot the enemy on the screen. So if everything is hard coded, and not knowing the exact type of the enemy, it can be difficult to deal with.

However, suppose I create a random number generator, each possible enemy class is replaced by a number and can be returned by the random number generator.

This number can then be sent to the factory object, which returns a dynamically created enemy.

So, the main concept of MOL is very important, and we want to be able to select classes at runtime, which is what the factory model can provide.

#何时使用工厂方法模式?

You can use the factory method pattern when you do not know what type of object is required.

However, it is important to note that all potential classes have the same subclass hierarchy, which means that there is the same parent class on the inheritance path.

You can use Factory mode to centralize the code selected by the category. Or if you don't want the user to know every possible subclass.

4.1.4JavaScript Single-case mode# What is a singleton mode?

Use singleton mode when you want to avoid instantiating multiple objects. Singleton allows only one object to be instantiated from a class.

Now you may ask yourself, when will I want to do this? In fact, there are many scenes.

We've demonstrated that Scrabble uses a class to hold all possible letters, and Scrabble is a very common board game, where using singleton mode is a smart choice.

This singleton class contains all possible scrabble letters so that the player can use the Singleton class to get all the letters, which can be requested by different players simultaneously.

The singleton allows each player to share the same alphabetical list, and each player can stitch his or her words according to the alphabetical list.

4.1.5JavaScript prototype Mode#什么是原型模式?

This is the prototype mode when you want to generate objects by cloning or copying objects.

Prototype mode allows you to add a child class instance of a known parent class at run time.

Prototype mode can be used when there are many classes that need to be used only at run time. One of the benefits of prototype mode is that it reduces the creation of multiple subclasses.

4.2 Structural Mode

This type of pattern describes the different ways to add functionality to an existing object, simply put, this pattern focuses on the interface implementation pattern of the decoupled object as follows:

    • Adapter mode

    • Bridging mode

    • Combination mode

    • Decorator mode

    • Appearance mode

    • Enjoy meta mode

    • Proxy mode

4.2.1JavaScript Adapter Design mode

#适配器模式的作用

Adapter design mode allows the use of two completely incompatible interfaces to work together, as well as the names of different interfaces.

Suppose you have only two plugs on the wall, but you want to connect a three-seat plug, you need an adaptor.

When the customer expects to use the target interface is two plugs, but you only have three plug, this is the adapter will perform the operation of the three to convert into two seats.

The adapter mode allows you to use any existing interface to adapt to the target interface.

From another point of view, any class can work together as long as the adapter solves the problem that all classes must implement the same interface.

4.2.2JavaScript Bridging Mode

#什么是桥接模式?

The official definition separates the abstraction from its implementation, so the two can change independently.

This pattern is used to separate the abstraction from its implementation so that both can be modified independently. This pattern contains an interface for bridging abstract classes and implementing classes. With bridging mode, both types can be modified without affecting each other.

#桥接模式实现指南

Bridging mode is used when you want to avoid permanent binding between abstractions and their implementations.

Both abstractions and their implementations should be extensible through subclasses. When an abstract implementation changes, the caller should not be affected, and the caller does not need to recompile.

You can choose this mode when you need to share an implementation between multiple objects.

Finally, we want to hide the abstract implementation entirely from the caller.

4.2.3JavaScript Combination Mode

The composition pattern looks very complex from the definition, and once it is used it feels reasonable.

It allows uniform processing of a single object and object combination, which is a typical definition of a composite design pattern.

The composition pattern can be expressed as a partial-whole hierarchy. The components of the structure can also be divided into smaller components.

A more logical definition is that the composite design pattern is used to structure the data or to separate each part of the entire object from each other's operations.

4.2.4JavaScript Decorative Mode

#什么是装饰模式?

Dynamically attaches additional functionality to an object, and adornment mode can be extended without inheritance.

This pattern belongs to the structural design pattern category, also known as the packaging mode, and the decorative design pattern solves the problem of adding additional functionality without changing the existing structure of the object.

In addition, the pattern creates an adorner class that wraps the original class and adds new behaviors or actions to the object at run time.

# Implementation Guide for decorating patterns

When you choose this mode, you need to dynamically add new functionality to a single object without affecting other objects.

For example, in some cases it can be difficult to add new functionality to legacy code, and it can be easier to modify the code with a decorator.

Implementing a feature extension through inheritance produces a large number of subclasses, and it is possible that these subclasses are not enough to cover all the features that need to be extended.

When a class definition cannot be viewed or cannot be inherited, the adornment mode needs to be selected.

For example, although the class is encapsulated and cannot be modified, it can still be extended through the adornment mode, and I am sure you have also encountered situations where the extension of functionality cannot be achieved through inheritance, in which case the adornment mode is selected.

4.2.5JavaScript appearance mode

#什么是外观模式?

Provides a unified interface for a set of interfaces in a subsystem. The appearance pattern defines a higher-level interface that makes the subsystem easier to use. The term appearance comes from the French fa?ade, meaning the front or face.

In a nutshell, the appearance pattern hides the complexity of the subsystem's implementation, providing us with a clean interface. This interface is responsible for invoking the functionality of an existing subsystem.

#外观模式实现指南

When we want to provide a simple interface to the subsystem, we need to use the appearance mode. With the development of subsystems, subsystems tend to become more complex.

When we apply some patterns, most patterns cause more classes to be created, which makes the subsystem more usable and easier to customize, but it becomes more difficult for business parties that don't need customization.

The appearance mode wraps the subsystem into a simple default interface that is sufficient to handle most situations.

In addition, you can choose the appearance mode when there are too many dependencies on the implementations of the business parties and subsystems.

In this case, the appearance mode separates the subsystem from the business party and other subsystems, thus improving the independence and portability of the subsystem.

So far, if the subsystems are too coupled, the dependencies between the subsystems can be simplified through the interfaces provided by the façade pattern.

4.2.6JavaScript enjoy meta mode

#什么是享元模式?

When you need to create a large number of similar objects need to use the enjoy meta-mode, where the large number is tens of thousands of magnitude rather than the usual touch of hundreds.

The enjoy meta-mode reduces the use of memory by sharing similar parts of objects and avoiding duplicate creation.

4.2.7JavaScript Proxy Mode

# What is proxy design mode?

A proxy is a class that will be used to restrict access to another class.

This may be for security reasons, and the proxy is used to determine which methods are available for the object that needs to be proxied.

4.3 Behavioral mode

This type of pattern describes how objects interact with the pattern as follows:

    • Responsibility chain Model

    • Command mode

    • Interpreter mode

    • Iterator mode

    • Broker mode

    • Memo Mode

    • Observer pattern

    • State mode

    • Policy mode

    • Template method Mode

    • Visitor mode

4.3.1JavaScript responsibility Chain Model

#什么是责任链模式?

The chain of responsibility pattern has a set of objects that are expected to solve the problem, and if the first object cannot resolve it, the data is passed to the next data in the chain of responsibility.

The request is processed through multiple recipient objects to avoid coupling the sender of the request to its recipient. Concatenates the received objects and passes the request until one of them is processed.

The chain of responsibility model creates a series of recipient objects for the request. In this mode, typically each sink contains a reference to another sink.

If a recipient cannot process the request, it passes the request to the next recipient.

4.3.2JavaScript Command mode

#什么是命令模式?

The command design pattern is a behavior design pattern whose objects are used to represent and encapsulate all the information needed to invoke a method later. This information includes the method name, the object that owns the method, and the value of the method parameter.

Basically, what it allows you to do is store the code list, execute later or multiple times, and usually use the command mode to undo the command.

When these encapsulated objects call the Execute () method, the business party or program executes the specified command or a piece of code.

The caller object then passes the command to the command receiver at the time of invocation, and the command receiver has the code that actually wants to execute, once the command is received from the caller.

For example, there is a "Turntvon" command object, then an "Devicebutton" object, and once the "Devicebutton" object is called, the "Turntvon" command is sent. All of these interfaces can use polymorphism, so whenever Turntvon is called, the method is executed by the command receiver.

4.3.3JavaScript Interpreter Mode

# What is the interpreter mode?

The interpreter pattern is easily ignored and is rarely used on the web.

However, it becomes very useful if used in conjunction with JavaScript reflection technology. It is used to convert a representation of data to another representation.

4.3.4JavaScript iterator Mode

# What is the iterator pattern?

The iterator pattern provides a uniform way to access different types of object collections.

For example, Array,arraylist and HashTable, these three collections contain objects of the same type, which can be used by iterators to fetch each element in the collection and do the same.

The iterator pattern does provide a uniform way to iterate through these different types of collections.

4.3.5JavaScript Broker-meter mode

#什么是中介者模式?

Used to handle communication between related objects. All communication is done by the intermediary, and the communication parties do not need to know any information about each other.

More strictly, the mediator pattern allows for loose coupling by encapsulating the interaction between different objects and communicating with each other, and the mediator pattern allows the behavior of each object to change independently of each other.

4.3.6JavaScript Memo Mode

#什么是备忘录模式?

To store the schema of the object's previous state, first, the memo pattern requires a memo object to store the different states of the object, different states, and some fields that have different values.

Then, the initial object used to read and write values from the current target memo object, creates a new Memo object and assigns the value to the current Memo object.

Finally, the interior is a ArrayList object used to hold all previous memo objects, and the ArrayList object is used to store and retrieve memo objects.

4.3.7JavaScript Viewer Mode

# When do I use observer mode?

Additional objects are required to receive updates when another object changes. For example, suppose we have an object or publisher representing thousands of stocks in the stock market, which can be done using the Observer pattern when the update needs to be sent to multiple subscribers.

#观察者模式的好处

Loose coupling. The object or Publisher does not have to know the presence of the observer or the Subscriber at all, and I divide this into two different concepts, because I think the publish-subscribe is more meaningful, but the basic term of OLP uses the object-observer.

#坏处

The only disadvantage of the observer pattern is that an object or publisher may send an update to the observer, which is irrelevant to the subscriber.

4.3.8JavaScript State mode

#什么是状态模式?

It allows an object to change its behavior when its internal state changes, so that the object appears to change the class it belongs to.

The state mode is divided into three main parts:

First, you will have a so-called "context" or "account," which is going to maintain an instance of the Concretestate subclass that will define the current state.

Then, you have the state, which defines a behavior interface that encapsulates the context-specific State association.

Finally, the State is specific, and each subclass implements the behavior related to the context state.

4.3.9JavaScript Policy Mode

# When do I use policy mode?

If you are defining a class that will have behavior similar to all other behaviors in the list, you can use the policy mode.

For example, some animals can fly, some animals cannot fly, and the similar behavior here is flying, whether or not the animal can fly.

You can select class objects from the following classes:

    • Can't fly

    • Fly with your Wings

    • Fly fast.

The strategy mode allows you to dynamically create new, different types of flying animals.

You can use policy mode when you need to dynamically determine the behavior you want to use.

# Additional benefits of using the policy model

It usually reduces the long list of conditions, so if you see the use of many different types of conditions, the policy pattern can be helpful. Of course, duplicate code is also avoided.

The policy pattern prevents changes in other classes from affecting the current class. You can also hide complex and sensitive code from business parties.

Cons: Policy mode increases the number of objects and classes.

4.3.10JavaScript Template Method mode

#什么是模板方法模式?

Used to create a set of subclasses that perform similar methods.

To implement it, you need to create an abstract class that will contain a method called a template method.

Creates an abstract class that contains a method called a template, and the template method contains a series of method calls that each subclass object will invoke. In some cases, the subclass also overloads some inappropriate method calls.

4.3.11JavaScript Visitor Mode

# What is the visitor pattern?

The visitor pattern allows methods to be added to different types of classes-but they do not have to be of different types-they only increase complexity and do not have too many modifications to the class.

This can be done in a completely different way depending on the class you are using.

It can also be said that the visitor pattern can be extended to create an external class for an existing class to avoid modifying the original class.

Note: Mastering the basic knowledge of object-oriented concepts such as abstraction, inheritance, polymorphism, encapsulation, interfaces, classes, and abstract classes is important to better understand design patterns.

23 JavaScript 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.