Detailed description of the factory mode in javascript mode design mode type: factory Mode
Mode Description: One of the common modes used to dynamically create objects
Applicability: classes that need to be selected in a series of interchangeable subclasses during running
Note: The implementation of interfaces so that different sub-classes can be treated equally and use the factory mode properly, but do not stick to the form and understand the essence.
Key Point: Selector built with function/class/subclass
Essence: the use of a function as a selector
General Usage:
As an independent selector:
The Code is as follows:
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 a method as a class exists:
The Code is as follows:
Var MainClass = function () {}; // main class Constructor
MainClass. prototype = {
FactoryMode: function () {}// subclass Selector
}
Or implicit choice, that is, not based on the user's subjective choice:
The Code is as follows:
Var xmlRequest = function (){
If (this. isOffOnline ()){
Xhr = new OfflineHandler ();
} // If the network is unavailable at this time, create a cacheable AJAX object
Else if (this. isHightLatency ()){
Xhr = new QueuedHandler ();
} // If the network latency is large, create an AJAX object in queue format
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 smooth operation in the future.
Return xhr;
}
Extension:
The essence of the factory mode is the application of the selector. The selector can be used as an object, function, class, and parameter.
Function selection, such:
The Code is as follows:
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:
The Code is as follows:
Var suitableClass = function (){
If (match condition A) return Class1;
Else if (match condition B) return Class2;
Else return ClassComm;
}
Parameter Selection:
The Code is as follows:
Function Country (country ){
If (country = "China ")
This. config = {}; // set basic parameter 1
Else if (contry = "America ")
This. config = {}; // set parameter 2
Else if ()
.../And so on
}
Country. prototype = {};