Home >Web Front-end >JS Tutorial >JavaScript design pattern classic simple factory pattern code example

JavaScript design pattern classic simple factory pattern code example

黄舟
黄舟Original
2017-03-20 11:08:021301browse

SimpleFactory pattern is a method that determines which class instance to create, and these instances often have Identical interface. This pattern is mainly used when the type to be instantiated is not determined at compile time, but is determined at execution time. To put it simply, it's like the beverage machine in the company's pantry. You want coffee or milk depending on which button you press.

The simple factory mode is also very useful when creating ajax objects.

This library provides several ajax request methods, including get and post of xhr objects, as well as cross-domain use jsonp and iframe. For convenience of use, these methods are abstracted into the same interface.

var request1 = Request(‘cgi.xx.com/xxx’ , ”get’ );
request1.start();
request1.done( fn );
var request2 = Request(‘cgi.xx.com/xxx’ , ”jsonp’ );
request2.start();
request2.done( fn );

Request is actually a factory method. As for whether to generate an instance of xhr or jsonp Instance. is determined by subsequent code.

In fact, in js, the so-called constructor is also a simple factory. I just approved a new piece of clothing. Let’s take off this piece of clothing and take a look inside.

Through this code, new can be perfectly simulated in browsers such as Firefox and Chrome.

       function A( name ){
this.name = name;
}
function 
Object
Factory(){
var obj = {},
Constructor = 
Array
.prototype.shift.call( arguments );
obj.
proto
 =  typeof Constructor .prototype === ‘number’  ? Object.prototype
:  Constructor .prototype;
var ret = Constructor.apply( obj, arguments );
return
 typeof ret === ‘object’ ? ret : obj;
}
var a = ObjectFactory( A, ‘svenzeng’ );
alert ( a.name );  //svenzeng

This code comes from the relevant instructions of es5's new and constructor. You can see that, The so-called new itself is just a process of copying and rewriting an object, and what is generated is determined by the parameters passed in when calling ObjectFactory.

Related articles:

Detailed explanation of the classic JavaScript design pattern, the strategy pattern

Detailed explanation of the classic JavaScript design pattern, the singleton pattern

Detailed introduction to the observer pattern of JavaScript design patterns

The above is the detailed content of JavaScript design pattern classic simple factory pattern code example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn