Member-only story
Singleton & Factory Patterns With TypeScript
The singleton and factory design pattern, implemented with TypeScript. Explained with a hairdresser and an ice creams shop examples.

Of all the design patterns I learned in engineering school, the singleton and factory are probably those I use the most in my day-to-day programming activities. Sometimes I even mix the two to double the fun 😜.
In this blog post, I will show you how to implement these patterns with TypeScript.
Singleton
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance (source).
A singleton is probably like your hairdresser. When you need a haircut, you do not want to go to a salon and get any new professional, even though she/he shares the same skills as yours but, you exactly want yours because she/he knows already your favorite settings ✂️.
Such a pattern can be implemented by defining the constructor
of a class
as private
, making it de facto not accessible outside the class declaration, and by providing only one single instance of the object which have been made static
.
export class Hairdresser {
private static instance: Hairdresser | undefined = undefined;
private constructor() {}
static getInstance(): Hairdresser {
if (!Hairdresser.instance) {
Hairdresser.instance = new Hairdresser();
}
return Hairdresser.instance;
}
}
Using the above snippet, we are not able to get any new hairdressers. Trying to instantiate a new object leads to an error.
// TS2673: Constructor of class 'Hairdresser' is private and only accessible within the class declaration.
const hairdresser: Hairdresser = new Hairdresser();
On the contrary, accessing the instance will always return the first object which has been initialized.
const hairdresser: Hairdresser = Hairdresser.getInstance();
Factory
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating…