_javascript techniques for the factory and constructor patterns of JavaScript design patterns

Source: Internet
Author: User

What is a pattern

Before preparing for the final exam, the trouble and the pernicious, really idle to update the article, today and you talk about the design patterns in JavaScript.

First, what we need to know is that the pattern is a reusable solution, and the reverse pattern is a bad solution for a problem.

JS Anti-pattern Common examples

1. Passing strings to settimeout and setinterval, rather than functions, triggers the internal use of eval ().
2. Define a large number of variables in the global context pollution global namespaces
3. Modify the prototype of the object class
4. Use JS inline form, the JS code embedded in the HTML file cannot be included in the External Unit test tool.
5. Misuse of document.write, if the page is loaded after the completion of Docume.write, it will rewrite our page, you can use document.createlement instead of the docume.write as far as possible.

Categories of Design Patterns

Create design pattern

The creation design pattern focuses on working with object creation mechanisms to create objects in a way that is appropriate for a given situation. Attributes that fall into this category include:

Constructor constructors, factory factories, abstract abstractions, prototype prototypes, singleton single cases, and builder generators

Structural design pattern

Structured patterns are related to object composition and can often be used to find simple ways to establish relationships between different objects.
The patterns that fall into this category include:

Decorator decorator, façade appearance, flyweight, adapter adapter, and proxy proxy

Behavioral Design Patterns

Behavioral patterns focus on improving or simplifying communication between different objects in the system.

Behavioral patterns include:

Iterator iterators, mediator intermediaries, observer observers, and visitor visitors

Factory (Factory) mode

In order to solve the problem of many similar object declarations, we can use a method called Factory pattern, which is to solve the problem that the instantiation object produces a lot of repetition.

Copy Code code as follows:

<script type= "Text/javascript" >
function CreateObject (name,age,profession) {//Set instantiated
var obj = new Object ();
Obj.name = name;
Obj.age = age;
Obj.profession = profession;
Obj.move = function () {
Return this.name + "at" + This.age + ' engaged in ' + this.profession;
};
return obj;
}
var test1 = CreateObject (' TRIGKIT4 ', +, ' programmer ');//First Instance
var test2 = CreateObject (' Mike ', ', ' Engineer ');//The second instance
Alert (Test1.move ());
Alert (Test2.move ());
</script>

Classification of factory patterns

The factory model is divided into simple factories, abstract factories, and intelligent factories, and the factory model does not display the requirement to use a constructor.

Simple Factory Pattern: Use a class (usually a monomer) to generate an instance.
Complex Factory pattern: use subclasses to determine which instances of a particular class A member variable should be.

The benefits of the factory model

The main benefit is that you can eliminate the coupling between objects by using engineering methods instead of the new keyword. Centralize all the instantiated code in one place to prevent code duplication.
the disadvantages of the factory model

Most classes better use the New keyword and constructor to make your code easier to read. Without having to look at the factory method to know.
The factory pattern solves the problem of duplicate instantiation, but there is also the problem of identifying the problem, because it is impossible to figure out exactly which object they are an instance of.

Copy Code code as follows:

Alert (typeof test1); Object
Alert (test1 instanceof Object); True

When to use Factory mode?

The Factory mode is used primarily in the following scenarios:

1. When an object or component involves high complexity
2. When you need to easily generate different instances of objects based on the different environments you are in
3. When working with many small objects or components that share the same properties

Constructor (builder) mode

Constructors (constructors) can be used in ECMAScript to create specific objects. This pattern can just solve the problem that the above Factory mode does not recognize object instances.

Copy Code code 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 ', 2014,20000);
var BMW = new Car ("BMW", 2013,12000);
Alert (Benz instanceof car); Clearly identified him as belonging to Car,true.

Console.log (Benz.run ());
Console.log (Bmw.run ());
</script>

The method of using constructors solves the problem of repeated instantiation and solves the problem of object recognition, which differs from Factory mode in that:

1. The constructor method does not display the creation object (new object ());
2. Assign properties and methods directly to the This object;
3. No Renturn statements.

There are some specifications for constructors ' methods:

1. The function name and the instantiated constructor name are the same and uppercase, (PS: not mandatory, but so write to help distinguish between constructors and ordinary functions);
2. To create an object from a constructor, you must use the new operator.
Since you can create an object from a constructor, where does the object come from and where does the new object () execute? The process of execution is as follows:

1. When the constructor is used and the new constructor (), the new Object () is executed in the background;
2. The scope of the constructor is given to the new object (that is, the object that is created by new object), and the This in the body of the function represents the object that came out of the.
3. Execute the code within the constructor;
4. Return the new object (background returned directly).

Constructor with prototypes (constructors)

JS has a property named prototype. When you call the JS constructor to create an object, the new object has all the properties of the constructor prototype. In this way, you can create multiple car objects and access the same prototypes.

Copy Code code 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 ', 2012,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.

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.