JavaScript Design Pattern learning Singleton_js object-oriented

Source: Internet
Author: User
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 ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.