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:
CopyCode 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:Copy codeCode: 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:
Copy code 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:Copy codeThe 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:
Copy code 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:
Copy code 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 = {};