1. Purpose of Singleton Pattern
The singleton pattern is often used to manage resource-sensitive objects, such as: database connection objects, registry objects, thread pool objects, etc. If multiple such objects exist simultaneously, it will cause various inconsistencies and troubles (you certainly don't want database duplicate connection exceptions to happen)
From Ayqy: Design Patterns - Singleton Pattern
In addition, the singleton pattern can also be used to reduce memory overhead (ensuring there's only one huge object)
2. Simplest Singleton Pattern
var singleton = {
// attr: val
}
Yes, that's simple. The object pointed to by singleton is unique, there's no way to create such an object through other means (deep copy doesn't count, because the premise of copying is that such an object already exists). Compared with singleton implemented via constructor approach, object literals have natural advantages—it's "one-time"
This singleton has the disadvantage of strong dependencies (tight coupling), dependency relationships are confined within the object literal, and there's even no way to pass parameters during initialization (the singleton itself is a fully functional object (module), if unable to pass parameters during initialization, it will inevitably affect its functionality)
3. General Singleton Pattern
Can combine with module pattern to fix the above problems, for example:
var singleton = (function() {
var obj; // Reference to singleton
function init() {
// Private attributes
// var attr = val
return {
// Public attributes
// attr: val
}
}
return {
getInstance: function() {
if (!obj) {
obj = init();
}
return obj;
}
}
})();
// Usage
var mySingleton = singleton.getInstance();
// mySingleton.xxx
singleton.getInstance() is the global access entry point, objects obtained from this entry point are all the same. If lazy initialization is not needed, there's no need to provide getInstance interface, just return the singleton object directly. Of course, most of the time, singleton pattern means huge objects, lazy initialization is very necessary
4. Purpose of Singleton Pattern in JavaScript
JS in browser environment is single-threaded, doesn't need to manage critical resources, and there are no resource-sensitive large objects (database connection objects, registry objects, thread pool objects, etc.). Looking at it this way, singleton pattern in JS seems useless.
Fact is indeed so, the only purpose of singleton pattern in JS may be managing huge objects, avoiding memory consumption of multiple huge objects existing simultaneously, such as jQuery-like top-level namespaces, and various level sub-namespaces, managing with singleton pattern can avoid confusion
References
-
"JavaScript Design Patterns"
No comments yet. Be the first to share your thoughts.