This article mainly introduces the factory mode and constructor mode of the JavaScript design mode. It also describes the categories of the design mode, such as the creation mode, structure mode, and behavior design mode, for more information, see
What is mode?
A while ago, I was preparing for the final exam. I am so sad that I have no time to update my article. Today I will talk to you about the Design Pattern in javascript.
First, we need to know that the pattern is a reusable solution, and the reverse pattern is a bad solution to a specific problem.
Common examples of js anti-Pattern
1. Pass a string to setTimeout and setInterval instead of a function, which triggers internal use of eval.
2. Define a large number of variables in the global context to pollute the global namespace
3. Modify the Object class prototype
4. js is used in the internal connection mode. js code embedded in HTML files cannot be included in the external unit test tool.
5. Misuse of document. write. If you execute commit E. write after the page is loaded, it will overwrite the page where we are located. You can use document. creatElement instead, try not to use commit E. write.
Design Pattern category
Creation Design Mode
The creation design mode focuses on the object creation mechanism and creates objects in a way suitable for a given situation. Attributes of this category include:
Constructor, Factory, Abstract, Prototype, Singleton, and Builder
Structural Design Mode
The structure pattern is related to the object combination. It can be used to find a simple method to establish a relationship between different objects.
The following modes are available:
Decorator, Facade appearance, Flyweight Meta, Adapter, and Proxy
Behavior Design Pattern
Behavior patterns focus on improving or simplifying communication between different objects in the system.
Behavior patterns include:
Iterator, Mediator intermediary, Observer, and Visitor
Factory Mode
To solve the problem of multiple similar object declarations, we can use a method called the factory pattern to solve the problem of generating a large number of duplicates for the instantiated object.
The Code is as follows: