Singleton
The Code is as follows:
/* Basic Singleton .*/
Var Singleton = {
Attribute1: true,
Attribute2: 10,
Method1: function (){
},
Method2: function (arg ){
}
};
One of the main purposes of the single-piece mode is the namespace:
/* GiantCorp namespace .*/
Var GiantCorp = {};
GiantCorp. Common = {
// A singleton with common methods used by all objects and modules.
};
GiantCorp. ErrorCodes = {
// An object literal used to store data.
};
GiantCorp. PageHandler = {
// A singleton with page specific methods and attributes.
};
Use closures to implement private methods and private variables in the single-piece mode:
GiantCorp. DataParser = (function (){
// Private attributes.
Var whitespaceRegex =/\ s + /;
// Private methods.
Function stripWhitespace (str ){
Return str. replace (whitespaceRegex ,'');
}
Function stringSplit (str, delimiter ){
Return str. split (delimiter );
}
// Everything returned in the object literal is public, but can access
// Members in the closure created above.
Return {
// Public method.
StringToArray: function (str, delimiter, stripWS ){
If (stripWS ){
Str = stripWhitespace (str );
}
Var outputArray = stringSplit (str, delimiter );
Return outputArray;
}
};
}) (); // Invoke the function and assign the returned object literal
// GiantCorp. DataParser.
Implement the Lazy Instantiation single-piece mode:
MyNamespace. Singleton = (function (){
Var uniqueInstance; // Private attribute that holds the single instance.
Function constructor () {// All of the normal singleton code goes here.
...
}
Return {
GetInstance: function (){
If (! UniqueInstance) {// Instantiate only if the instance doesn't exist.
UniqueInstance = constructor ();
}
Return uniqueInstance;
}
}
})();
MyNamespace. Singleton. getInstance (). publicMethod1 ();