This post about design pattern covers one of the most popular creational patterns, the singleton pattern, and how to implement it in JavaScript.
To make this happen the implementation must prevent the class to be instantiated via a new statement, e.g.
The heart of this implementation is the
Intent and Applicability
The intent of the singleton pattern is that only one instance of a specified class exists within a system. Although you could use a global variable as an instance of a class to be accessible globally, it might make sense to let the object itself be responsible for its uniqueness, that means it cannot be instantiated multiple times.General Concept
The singleton pattern can be implemented within one class. The class uses a unique point of access, thegetInstance()
method.To make this happen the implementation must prevent the class to be instantiated via a new statement, e.g.
var newObj = new SingletonClass());
Implementation
The concept can be implemented in this way:
function SingletonClass() {
if (SingletonClass.caller != SingletonClass.getInstance) {
throw new Error("SingletonClass can only be accessed by getInstance() method.");
} // Prevent class from being called by anything else than getInstance()
var _instance = null;
var singletonData = "ABC";
this.getSingletonData = function() {
return singletonData;
};
this.setSingletonData = function(newValue) {
singletonData = newValue;
};
}
SingletonClass.getInstance = function() {
if (this._instance == null) {
this._instance = new SingletonClass();
}
return this._instance;
}
The heart of this implementation is the
getInstance()
function. The first time it is called it instantiates a new object and assigns the (private) variable _instance
to it. The other core part of the implementation is the constructor of the class. It checks if the caller is something else then the class itself. In this case the class is not being generated. The result is the behavior that the class is being instantiated only once during the first call to getInstance()
.
Kommentare
Kommentar veröffentlichen