Direkt zum Hauptbereich

Posts

Es werden Posts vom März, 2013 angezeigt.

Design Patterns in JavaScript: The Singleton pattern

This post about design pattern covers one of the most popular creational patterns, the singleton pattern, and how to implement it in JavaScript. 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, the getInstance() 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("Singlet...