Singleton
One of the most used design patterns, Singleton makes sure that only one instance of a particular class is created, and provides a global point of access to that instance.
Singleton is most useful when you need a single object to coordinate other objects.
A singleton is usually implemented as a class that contains:
- a private constructor (so that only members of the same class can access it),
- a private static member,
- a static public method that returns a reference to the private static member.
Here's a class that represents the president as a singleton. Note the private static property holding the instance, the private constructor that can only be called from inside the class, and the GetInstance()
method that creates a single instance representing the president if it's null, or returns the previously created instance if it's not null:
1class President {
2 constructor(firstName, lastName, party) {
3 this.FirstName = firstName;
4 this.LastName = lastName;
5 this.Party = party;
6 }
7
8 static GetInstance() {
9 if (!this.instance) this.instance = new President("Donald", "Trump", "Republican");
10 return this.instance;
11 }
12
13 get LastName() { return this.LastName; }
14 get FirstName() { return this.FirstName; }
15 get Party() { return this.Party; }
16
17 toString() { return this.FirstName + " " + this.LastName + ", " + this.Party; }
18}
At call site, we'd call the GetInstance()
method to get the one and only instance. Note how trying to use the constructor directly doesn't compile because the constructor is private.
1// In JavaScript
2let constructed = new President("Bernie", "Sanders", "Democratic"); // Won't compile, constructor is private
3let one = President.getInstance();
4let two = President.getInstance();
5
6console.log(one);
7console.log(two);
8console.log(one === two); // Will return true as both variables point to the same instance
There are multiple legitimate scenarios for using singletons, including caching, logging, and hardware interface access.