Singleton

Singletons in TypeScript

A singleton[1] is a pattern that guarantees there is a single instance of an object in the system. A singleton can maintain a state which is shared across the entire system. Singletons abstract their internal workings from the rest of the system.

singleton
Singleton pattern

Singletons are common in business applications. They help model real-life business processes that involve shared resources.

Singletons in TypeScript

In Node.js – and TypeScript by association – singletons can be expressed as modules[2]. In Node, modules are effectively singletons[3]:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file.

In languages like Java, one must take care to prevent other developers from constructing new instances of singletons by declaring private constructors and using a static factory method (i.e. getInstance). The module system in Node.js offers a built-in mechanism to achieve the same effect.

Here is the general pattern for a singleton in TypeScript:

Source: Singleton.ts

/**
 * Singletons in TypeScript are best expressed as modules.
 *
 * @see http://www.oodesign.com/singleton-pattern.html
 */

export function doSomething():void {
        console.log("Hello world");
}

Source: client.ts

import * as mySingleton from './Singleton';

mySingleton.doSomething();

Case study: configuration manager

Any application worth its number of lines of code requires some configuration. The configuration may come from a file, environment variables, preferences stored on a server, and so on.

It is a poor practice to repeat configuration access code everywhere in the system. If the physical location of configuration ever changes one would have to update many different files and lines of code. To solve this, developers implement a singleton for managing configuration.

Example: Configuration manager singleton in TypeScript

It is unlikely that one may have to build a configuration manager from scratch. There is a ton of Node libraries for this, with node-config[4] being one such module.

However, for the sake of discussion let’s try and build one and see how it would work.

Source: ConfigurationManager.ts

const MAX_NUMBER_OF_CONNECTIONS = 'MAX_NUMBER_OF_CONNECTIONS';

const DEVICES_PER_CONNECTION = 10;

export function getMaxNumberOfConnections():number {
    return process.env[MAX_NUMBER_OF_CONNECTIONS] as number;
}

export function getMaxConcurrentDevices():number {
    return DEVICES_PER_CONNECTION * getMaxNumberOfConnections();
}

Source: client.ts

import * as config from './ConfigurationManager';

console.log(config.getMaxNumberOfConnections());
console.log(config.getMaxConcurrentDevices());

Singletons and concurrency

Singletons are shared across the system, and so is their state. In languages like Java this presents a challenge in a multithreaded environment. Node.js concurrency model, however, is different. In Node, there is a single CPU thread – meaning that no more than one thread has access to a singleton’s state.

Singletons and distributed environments

Beleive it or not, I once failed a job interview by pointing out that in a distributed and cloud computing there could be more than one physical instance of a singleton.

Let’s imagine a cloud deployment of a Node.js application. As is common with many applications out there, it is architected around a few singletons. A cloud architecture can auto-scale – which means that there could be multiple instances of the application, and therefore multiple instances of singletons.

Logically, these auto-scaled singletons are still singletons. However, for them to behave like true singletons, they must share state. One solution would be to use a cache service like Redis or persist state in a database. That depends on your requirements and is beyond the scope of this article.

Further reading

There is an old saying that if you ask one software engineer about the best way to accomplish a task you will get one answer. If you ask two, you will get three answers. Consider the StackOverflow question on “How to define a Singleton in TypeScript”[5] as one example of such a debate.

While I believe that using modules is the best approach to singletons in TypeScript (and Node.js in general), there are other ideas out there. The purpose of this article was to demonstrate a pattern and suggest an implementation. Ultimately, it is up to the reader to make the final decision.

Featured image credit Nan Palmero via Flickr.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s