Usefall
The Singleton Pattern
Purpose
Many things of a kind may exist.
I want to ensure I always work with the same single one of them.
Lazy Wolf
Ah my house is a mess!
Maybe it’s because I use a new dish every time I eat…
class LazyWolf {
eat(dish) {
console.log("Nom nom nom");
}
}
class Dish {}
const lazyWolf = new LazyWolf();
let breakfastDish = new Dish();
breakfastDish.food = "apples";
lazyWolf.eat(breakfastDish);
let dinnerDish = new Dish();
dinnerDish.food = "grapes";
lazyWolf.eat(dinnerDish);
Angry House
I am angry because you made a mess.
Just make it impossible to use another dish in the house!
Lazy Wolf
How do I do that?
Also you if you are angry while you are smiling!?
Angry House
This is my angry face.
Make it impossible for yourself to call the
new Dish()
constructor directly.Create a static factory method that always gives you the same dish instance.
class Dish {
static isBeingCreatedByFactory = false;
static singleInstance = null;
constructor() {
if (!Dish.isBeingCreatedByFactory) {
throw new Error("Not allowed to create Dish.");
}
}
static getInstance() {
if (!Dish.singleInstance) {
Dish.isBeingCreatedByFactory = true;
Dish.singleInstance = new Dish();
Dish.isBeingCreatedByFactory = false;
}
return Dish.singleInstance;
}
}
const lazyWolf = new LazyWolf();
const breakfastDish = Dish.getInstance();
breakfastDish.food = "apples";
lazyWolf.eat(breakfastDish);
const dinnerDish = Dish.getInstance();
dinnerDish.food = "bananas";
lazyWolf.eat(dinnerDish);
Lazy Wolf
Wow, It’s impossible create a new dishes now.
There is only one single dish instance in the house now.
I keep getting back and using the same single dish for my food.
My house is finally clean!
Angry House
If you mess me up again, I will mess you up.
You are welcome.
Solution
Make it so only a single instance of a kind may exist (a singleton).
Make instance creation only possible via a function that returns the same single instance.
Notes, Credits and References
- You can just mark the constructor as private to prevent others from calling it directly. Javascript does not have private constructors.
- House sticker created by Stickers - Flaticon
- Bear (Lazy Wolf) sticker created by Stickers - Flaticon