The Singleton Pattern

The Singleton pattern is thus known because it restricts instantiation of a class to a single object. Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist. In the event of an instance already existing, it simply returns a reference to that object.

Singletons differ from static classes (or objects) as we can delay their initialization, generally because they require some information that may not be available during initialization time. They don't provide a way for code that is unaware of a previous reference to them to easily retrieve them. This is because it is neither the object or "class" that's returned by a Singleton, it's a structure. Think of how closured variables aren't actually closures - the function scope that provides the closure is the closure.

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

We can implement a Singleton as follows:

var mySingleton = (function () {

  // Instance stores a reference to the Singleton
var instance; function init() { // Singleton // Private methods and variables
function privateMethod(){
console.log( "I am private" );
} var privateVariable = "Im also private"; var privateRandomNumber = Math.random(); return { // Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
}, publicProperty: "I am also public", getRandomNumber: function() {
return privateRandomNumber;
} }; }; return { // Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () { if ( !instance ) {
instance = init();
} return instance;
} }; })(); var myBadSingleton = (function () { // Instance stores a reference to the Singleton
var instance; function init() { // Singleton var privateRandomNumber = Math.random(); return { getRandomNumber: function() {
return privateRandomNumber;
} }; }; return { // Always create a new Singleton instance
getInstance: function () { instance = init(); return instance;
} }; })(); // Usage: var singleA = mySingleton.getInstance();
var singleB = mySingleton.getInstance();
console.log( singleA.getRandomNumber() === singleB.getRandomNumber() ); // true var badSingleA = myBadSingleton.getInstance();
var badSingleB = myBadSingleton.getInstance();
console.log( badSingleA.getRandomNumber() !== badSingleB.getRandomNumber() ); // true // Note: as we are working with random numbers, there is a
// mathematical possibility both numbers will be the same,
// however unlikely. The above example should otherwise still
// be valid.

What makes the Singleton is the global access to the instance (generally through MySingleton.getInstance()) as we don't (at least in static languages) call new MySingleton() directly. This is however possible in JavaScript.

In the GoF book, the applicability of the Singleton pattern is described as follows:

  • There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

The second of these points refers to a case where we might need code such as:

mySingleton.getInstance = function(){
if ( this._instance == null ) {
if ( isFoo() ) {
this._instance = new FooSingleton();
} else {
this._instance = new BasicSingleton();
}
}
return this._instance;
};

Here, getInstance becomes a little like a Factory method and we don't need to update each point in our code accessing it. FooSingleton above would be a subclass of BasicSingleton and implement the same interface.

Why is deferring execution considered important for a Singleton?:

In C++ it serves to isolate from the unpredictability of the order of dynamic initialization, returning control to the programmer.

It is important to note the difference between a static instance of a class (object) and a Singleton: whilst a Singleton can be implemented as a static instance, it can also be constructed lazily, without the need for resources nor memory until this is actually needed.

If we have a static object that can be initialized directly, we need to ensure the code is always executed in the same order (e.g in case objCar needs objWheel during its initialization) and this doesn't scale when you have a large number of source files.

Both Singletons and static objects are useful but they shouldn't be overused - the same way in which we shouldn't overuse other patterns.

In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system. Here is one example with the pattern being used in this context:

var SingletonTester = (function () {

  // options: an object containing configuration options for the singleton
// e.g var options = { name: "test", pointX: 5};
function Singleton( options ) { // set options to the options supplied
// or an empty object if none are provided
options = options || {}; // set some properties for our singleton
this.name = "SingletonTester"; this.pointX = options.pointX || 6; this.pointY = options.pointY || 10; } // our instance holder
var instance; // an emulation of static variables and methods
var _static = { name: "SingletonTester", // Method for getting an instance. It returns
// a singleton instance of a singleton object
getInstance: function( options ) {
if( instance === undefined ) {
instance = new Singleton( options );
} return instance; }
}; return _static; })(); var singletonTest = SingletonTester.getInstance({
pointX: 5
}); // Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );

Whilst the Singleton has valid uses, often when we find ourselves needing it in JavaScript it's a sign that we may need to re-evaluate our design.

They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a codebase. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.

Miller Medeiros has previously recommended this excellent article on the Singleton and its various issues for further reading as well as the comments to this article, discussing how Singletons can increase tight coupling. I'm happy to second these recommendations as both pieces raise many important points about this pattern that are also worth noting.

Learning JavaScript Design Patterns The Singleton Pattern的更多相关文章

  1. Learning JavaScript Design Patterns The Module Pattern

    The Module Pattern Modules Modules are an integral piece of any robust application's architecture an ...

  2. Learning JavaScript Design Patterns The Observer Pattern

    The Observer Pattern The Observer is a design pattern where an object (known as a subject) maintains ...

  3. Learning JavaScript Design Patterns The Constructor Pattern

    In classical object-oriented programming languages, a constructor is a special method used to initia ...

  4. AMD - Learning JavaScript Design Patterns [Book] - O'Reilly

    AMD - Learning JavaScript Design Patterns [Book] - O'Reilly The overall goal for the Asynchronous Mo ...

  5. use getters and setters Learning PHP Design Patterns

    w Learning PHP Design Patterns Much of what passes as OOP misuses getters and setters, and making ac ...

  6. Learning PHP Design Patterns

    Learning PHP Design Patterns CHAPTER 1 Algorithms handle speed of operations, and design patterns ha ...

  7. [Design Patterns] 3. Software Pattern Overview

    When you're on the way which is unknown and dangerous, just follow your mind and steer the boat. 软件模 ...

  8. [Design Patterns] 4. Creation Pattern

    设计模式是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结,使用设计模式的目的是提高代码的可重用性,让代码更容易被他人理解,并保证代码可靠性.它是代码编制真正实现工程化. 四个关键元素 ...

  9. JavaScript Design Patterns: Mediator

    The Mediator Design Pattern The Mediator is a behavioral design pattern in which objects, instead of ...

随机推荐

  1. POJ3613 Cow Relays [矩阵乘法 floyd类似]

    Cow Relays Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 7335   Accepted: 2878 Descri ...

  2. css之自动换行

    自动换行问题,正常字符的换行是比较合理的,而连续的数字和英文字符常常将容器撑大, 挺让人头疼,下面介绍的是CSS如何实现换行的方法 对于div,p等块级元素 正常文字的换行(亚洲文字和非亚洲文字)元素 ...

  3. Welcome

    唔.你好! 这里是 Evensgn 的笔记本. 我是 SD 省的一名高中 OIer,从初中就接触了 OI ,然而水平一直是弱弱哒. Evensgn 是我常用的 ID. 不忘初心,方能始终. E-mai ...

  4. [模拟]Codeforces509C Sums of Digits

    题目链接 题意:给n个数a[i], 要求b[i]每位数的和等于a[i], 并且b[i]要严格递增 求最小的b[i] b[0]最小一定是X9999...这样的形式 后面的b[i]位数一定大于等于前一个 ...

  5. c helloworld on zynq

    A linux os runs on zynq board. I want ro run a hello world c program on it. I linked zynq board to a ...

  6. Java程序发展之路

  7. 如何忽略usb host 模式设备连接确认对话框

    <li class="alt"><span><span>package android.hardware.usb;  </span> ...

  8. 【HDOJ】1074 Doing Homework

    最开始以为是贪心,不过写到一半发现不对,看了一下讨论,知道需要使用状态压缩DP,现在还没有使用深搜实现(据说可以)晚上实现一下,道理应该是类似的.前面做八数码,至今未果,就说需要状态压缩.这个太神奇了 ...

  9. hadoop面试时可能遇到的问题

    面试hadoop可能被问到的问题,你能回答出几个 ? 1.hadoop运行的原理? 2.mapreduce的原理? 3.HDFS存储的机制? 4.举一个简单的例子说明mapreduce是怎么来运行的 ...

  10. 全新 D 系列虚拟机型号

    Kenaz KwaAzure计算运行时项目经理 今天,我们宣布将发布名为D系列的Windows Azure 新VM型号,并支持虚拟机和 Web/Worker Role.这些虚拟机型号最多可以提供 11 ...