One of the more popular JavaScript patterns is the singleton. The singleton pattern can be very simple to implement, but can take on many different forms which will be shown below.
When should I use the singleton pattern?
The singleton pattern perfect for when you only need a single instance of an object. The functionality should never be altered when you create new instances of that object. If you need to change functionality after instantiation, then you should choose a different JavaScript design pattern.
Singleton pattern is good for:
- When you need an object with only one instance
- Namespacing
- Reducing global resources
- Organizing code
- Maintenance
- Handling AJAX requests
Basic implementations:
|
1 2 3 4 5 6 7 8 9 10 |
// Object literal
var Namespace = {
property: true,
method: function() {
}
} |
Above is the simplest form of the singleton pattern. There is no need to instantiate using the new operator as this is an object literal. As you can see, the object literal contains both properties and methods and a variable to access the object. We can take this a step further and build a singleton with both public and private members.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// Private and public members
var Namespace = function() {
// Private Properies
var privateProperty1 = true;
var privateProperty2 = false;
// Private Methods
function privateMethod1() {
}
function privateMethod2() {
}
return {
// Public Properies
publicProperty1: 9,
publicProperty2: false,
// Public Methods
publicMethod1: function() {
},
publicMethod2: function() {
},
}
} |
Here we have private properties and methods that are only accessible within the function and are not available outside the function. We then return an object literal with public properties and methods, which are accessible outside the function using dot notation (ex: Namespace.publicMethod1() or Namespace.publicProperty2).