JavaScript Design Pattern Learning Singleton_js Object oriented

Source: Internet
Author: User
Copy Code code as follows:

/* Basic Singleton. */
var Singleton = {
Attribute1:true,
Attribute2:10,
Method1:function () {
},
Method2:function (ARG) {
}
};
One of the most important uses of a single piece mode is the namespace:
/* Giantcorp namespace. */
var Giantcorp = {};
Giantcorp.common = {
A Singleton with common methods used by the all objects and modules.
};
Giantcorp.errorcodes = {
An object literal used to store data.
};
Giantcorp.pagehandler = {
A Singleton with page specific methods and attributes.
};
Implement private and private variables in a single piece mode using closures:
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 are public, but can access the
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 to
Giantcorp.dataparser.
Implement 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 ();
Related Article

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.