Direkt zum Hauptbereich

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("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().

Detailed Discussion

A more detailed theoretical discussion on the singe pattern can be found at http://en.wikipedia.org/wiki/Singleton_pattern

Kommentare

Beliebte Posts aus diesem Blog

CQRS - Command Query Responsibility Segregation

A lot of information systems have been built with a data manipulation focus in mind. Often CRUD (create, read, update delete) operations built on top of a predefined relational data model are the first functionalities that are implemented and lay out as a foundation for the rest of an application. This is mainly because when we think about information systems we have a mental model of some record structure where we can create new records, read records, update existing records, and delete records. This had been learned throughout the last decade of data centric and transaction oriented IT systems. This approach often leads to shortcomings when it comes to query and analyze the system's data. Classical layered architecture This is where CQRS comes into the game. CQRS stands for Command Query Responsibility Segregation and has been first described by Greg Young and later on by Martin Fowler. This architectural pattern calls for dividing the software architecture into two parts...

Creating load tests with Gatling instead of JMeter

I just came around a tool called Gatling (http://gatling-tool.org/) to create load tests for web applications. I used to use JMeter for a long time, but JMeter has weaknesses that Gatling doesn‘t have. JMeter uses a synchronous request approach. That means for every request JMeter generates, an internal thread is raised and therefore blocked until a response is being received or a timeout happens. This results in resource blocking on the load injector. The maximum number of threads is limited within a JVM - dependent on the underlying infrastructure -  and even if you are able to run a lot of parallel threads this will result in a high CPU and memory utilization. Although performance tweaking and scaling out to distributed testing might help in such a case, it makes testing more complex and error-prone. This behavior can result in distorted metrics. Think about a typical breakpoint load test. You want to determine, which is the maximum number of requests per second your tested ...

Device-Weiche in PHP

Anforderungen für Device-Weichen Je mehr Anforderungen an die Unterstützung von unterschiedlichen Devices kommen, desto öfter steht man vor der Frage, wie die verschiedenen Ausgabegeräte zwecks unterschiedliche Behandlung auf einer Seite unterschieden werden können, um dann z.B. jeweils eine Weiterleitung auf unterschiedliche Zielseiten vorzunehmen welche das entsprechende Device unterstützen, also eine sogenannte Device-Weiche oder Browser-Weiche. Klassische Use Cases sind hier: Je nach Device die "klassische" Website oder die mobile Site anzeigen Eine Landing Page erstellen, welche unterschiedliche mobile Devices zu unterschiedlichen Zielseiten (z.B. Subdomains) verzweigt Eine Redirect-Verteilerseite, welche mobile Devices in die verschiedenen Stores für einen mobile App Download weiterleitet Das letztgenannte Beispiel möchte ich hier einmal exemplarisch demonstrieren. Man stelle sich folgendes Szenario vor: Demo-Szenario Im Rahmen einer Web-Anwendung ...