The factory mode and constructor mode of the JavaScript design mode, and the javascript Design Mode

Source: Internet
Author: User

The factory mode and constructor mode of the JavaScript design mode, and the javascript Design Mode

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.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function createObject (name, age, permission sion) {// function instantiated in a centralized manner
Var obj = new Object ();
Obj. name = name;
Obj. age = age;
Obj. Merge sion = merge Sion;
Obj. move = function (){
Return this. name + 'at' + this. age + 'engaged' + this. Permission Sion;
};
Return obj;
}
Var test1 = createObject ('trigger4', 22, 'grammer '); // The First Instance
Var test2 = createObject ('Mike ', 25, 'engineer'); // The Second Instance
Alert (test1.move ());
Alert (test2.move ());
</Script>

Classification of factory models

Factory models are divided into simple factories, abstract factories, and smart factories. A constructor is not explicitly required for factory models.

Simple factory mode: Use a class (usually a single unit) to generate an instance.
Complex factory mode: subclass is used to determine the instance of a specific class for a member variable.

Benefits of the factory Model

The main advantage is that the coupling between objects can be eliminated by using engineering methods instead of the new keyword. Set all instantiated codes in one place to prevent code duplication.
Disadvantages of the factory Model

Most classes use the new Keyword and constructor to make the code easier to read. Instead of checking the factory method.
The factory mode solves the problem of repeated instantiation, but there is another problem, that is, the identification problem, because it is impossible to figure out which object they are actually instances.
Copy codeThe Code is as follows:
Alert (typeof test1); // Object
Alert (test1 instanceof Object); // true

When should I use the factory model?

The Factory mode is mainly used in the following scenarios:

1. When objects or components involve high complexity
2. When you need to easily generate different instances of Objects Based on Different Environments
3. When processing many small objects or components that share the same attributes

Constructor (Constructor) Mode

ECMAScript can use Constructor (constructor) to create specific objects. This mode solves the problem that the above factory mode cannot identify the object instance.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Car (model, year, miles) {// constructor Mode
This. model = model;
This. year = year;
This. miles = miles;
This. run = function (){
Return this. model + "has done" + this. miles + "miles ";
}
}
Var Benz = new Car ('benz', hz20000 );
Var BMW = new Car ("BMW", 2011,12000 );
Alert (Benz instanceof Car); // clearly identifies him from a Car, true

Console. log (Benz. run ());
Console. log (BMW. run ());
</Script>

The constructor solves the problem of repeated instantiation and object recognition. The difference between this mode and the factory mode is:

1. Create Object (new Object () not displayed in the constructor method ());
2. directly assign attributes and methods to this object;
3. There is no explain urn statement.

Constructor methods have some specifications:

1. The function name and the instantiated constructor name are the same and in upper case (PS: not mandatory, but this write will help distinguish between the constructor and common function );
2. Create an object through the constructor. The new operator must be used.
Since an Object can be created through a constructor, where does the Object come from and where new Object () is executed? The execution process is as follows:

1. When the constructor and the new Constructor () are used, the new Object () is executed in the background ();
2. Assign the constructor scope to the new Object (the Object created by the new Object (), and this in the function body represents the Object created by the new Object.
3. Execute the code in the constructor;
4. Return the new object (directly returned in the background ).

Constructor with prototype (Constructor)

Javascript has a property named prototype. After the js constructor is called to create an object, the new object will have all attributes of the constructor prototype. In this way, you can create multiple Car objects and access the same prototype.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Car (model, year, miles ){
This. model = model;
This. year = year;
This. miles = miles;
}
Car. prototype. run = function (){
Return this. model + "has done" + this. miles + "miles ";

};
Var Benz = new Car ('s350', 2010,20000 );
Var Ford = new Car ('Ford ', 2011,12000 );

Console. log (Benz. run (); // "S350 has done 20000 miles"
Console. log (Ford. run ());
</Script>

Now a single instance of run () can be shared among all Car objects.

Related Article

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.