Pattern type: Factory pattern
Pattern description: One of the common patterns, used to dynamically create objects
Scope of application: Classes that need to choose among a series of interchangeable subclasses during runtime
Notes : The implementation of the interface, so that different subclasses can 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 exist as a method of the class:
var MainClass=function(){};//Main class constructor
MainClass. prototype={
FactoryMode:function(){}//Subclass selector
}
Or implicit selection, that is, it is not selected based on 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 queue form AJAX object
else {
xhr=new SimpleHandler();
}//If the network Normally, create a simple AJAX object
interface.ensureImplements(xhr,AjaxHandler);
//Check whether the object implements the interface to ensure that 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 object selection, but also function selection, class selection, and parameter selection
Selection of functions, 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 of
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 parameter 1
else if(contry=="America")
this.config={};//Set parameter 2
else if()
..........//Wait
}
Country.prototype={};