Singleton Design Pattern is basically limiting our class so that
whoever is using that class can only create 1 instance from that class.
I create a private constructor which limits access to the instance of the class.
Than I create a getter method where we specify how to create&use the instance.
- I am using JAVA Encapsulation OOP concept.
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
let instance;
let counter = 0;
class Counter {
constructor() {
if (instance) {
throw new Error("You can only create one instance!");
}
instance = this;
}
}
const singletonCounter = Object.freeze(new Counter());
export default singletonCounter;