Before reading this article, it is recommended to read this article: Singleton Mode of JavaScript Design Patterns. After all, I personally feel that it is better to proceed step by step.
Factory pattern is divided into simple factory pattern and complex factory pattern. The former uses a class to generate an instance, usually a singleton. The latter uses a subclass to determine which class a member variable is a specific instance of. That is, the simple factory contains in complex factories.
Let’s talk about this factory in detail through a specific example.
Using Ajax technology to initiate asynchronous requests is a common task in web development today.
1 //implements AjaxHandler, creates a complex factory to execute a series of Ajax processes, which contains two simple factories
2 var SimpleHandler = function(){};
3
4 SimpleHandler.prototype = {
5 //The first simple factory performs Ajax creation, request, and sending. . . wait
6 request:function(method,url,callback,postVars){
7 var xhr = this.createXhrObject();
8 xhr.onreadystatechange = function(){
9 if(xhr.readyState != 4) return;
10 (xhr.status == 200) ?
11 //A global object callback is defined to perform the application of return parameters
12 callback.success(xhr.responseText,xhr.responseXML):
13 callback.failure(xhr.status);
14};
15 xhr.open(method,url,true);
16 if(method != "POST") postVars = null;
17 xhr.send(postVars);
18},
19 //The second simple factory creates XHR objects according to different situations. It can return a correct XHR object no matter what the situation is.
20 createXhrObject:function(){
21 var methods = [
22 function(){return new XMLHttpRequest();},
23 function(){return new ActiveXObject('Msxml2.XMLHttp');},
24 function(){return new ActiveXObject('Microsoft.XMLHttp');}
25 ];
26 for(var i = 0; i < 3; i++){
27 try{
28 methods[i]();
29 }catch(e){
30 continue;
31}
32 this.createXhrObject = methods[i]();
33 return methods[i]();
34}
35 throw new Error("Error!");
36}
37 }
38
Seeing this, the factory pattern is generally a further extension and application of the single pattern. The above example can be called like this:
1 window.onload = function(){
2 var myHandler = new SimpleHandler();
3 var callback = {
4 success:function(responseText,responseXML){alert("Success:" + responseXML);},
5 failure:function(statusCode){alert("Failure" + statusCode);}
6};
7 myHandler.request('GET','innerHTML.xml',callback);
8
9 };//Of course, the callback will be different depending on the situation.
By using the factory pattern instead of using the new keyword and concrete classes, you can centralize all instance code in one location.
Using the factory pattern, you can first create an abstract parent class, and then create factory methods in the subclass, thereby deferring the instantiation of member objects to more specialized subclasses, which can effectively prevent code duplication.