Pattern type: Factory pattern
Pattern description: One of the common patterns, used to dynamically create objects
Scope of application: Need to choose between a series of interchangeable subclasses during runtime Class
Notes: The implementation of the interface allows different subclasses to be treated equally. Use the factory pattern appropriately, but do not stick to the form and understand the essence.
Key points: Selectors built with functions/classes/subclasses
Essence: The use of functions as selectors
General usage form:
Exists as an independent selector:
function FactoryMode (index){
switch(index){
case "index1" :
return new Class1();break;
case "index2" :
return new Class2();break;
case "index3":
return new Class3();break;
default:return new ClassComm();break;
}
}
or Exists as a method of the class:
var MainClass =function(){};//Main class constructor
MainClass.prototype={
FactoryMode:function(){}//Subclass selector
}
Or implicit selection, that is, selection without the user’s subjective choice:
var xmlRequest=function(){
if(this.isOffOnline()){
xhr= new OfflineHandler();
}//If the network is not available at this time, Create a cacheable AJAX object
else if(this.isHightLatency()){
xhr= new QueuedHandler();
}//If the network delay is large, create a queued AJAX object
else {
xhr=new SimpleHandler();
}//If the network is normal, create a simple AJAX object
interface.ensureImplements(xhr,AjaxHandler);
//Check whether the object implements the interface to ensure Future work can proceed smoothly
return xhr;
}
Extension:
The essence of the factory pattern is the application of selectors. Selectors can not only be used as objects Selection can also be used as function selection, class selection, parameter selection
function selection, such as:
var addEvent=(function(){
if(!-[0,]){
return function(elem,type,handler){
elem[type handler.toString()]=handler;
elem.attachEvent("on" type,elem[type handler.toString]);
}}//if IE
else {
return function(elem,type,handler){
elem.addEventListener(type,handler,false);
}
}
})();//Avoid multiple judgments
Class selection:
var suitableClass=function(){
if(match condition A) return Class1;
else if(match condition B) return Class2;
else return ClassComm;
}
Parameter selection:
function Country(country){
if(country=="China")
this.config={};//Set basic parameters 1
else if(contry=="America")
this.config={};//Set parameter 2
else if()
.....//And so on
}
Country.prototype={};