The Singleton Class pattern

The Class pattern is quite quickly become the de facto pattern for creating abstractions of all types, including singletons and utility objects as well, so it may not always be the case that your class will need to be utilized as a conventionally OOP class with inheritance and instantiation. For example, we may wish to set up a utility object with a class definition so that we can define any initialization logic within the constructor and provide a semblance of encapsulation within its methods:

const utils = new class {
constructor() {
this.#privateThing = 123;
// Other initialization logic here...
}
utilityA() {}
utilityB() {}
utilityC() {}
};

utils.utilityA();

Here, we're creating and immediately instantiating a class. This is similar in spirit to the Revealing Module pattern where we utilize an IIFE to encapsulate initialization logic and the public API. Here, instead of achieving that encapsulation via a scope (and the resulting closure around private variables), we are using the straightforward constructor to define our initialization. We then are using the regular instance properties and methods to define both our private variables and our public interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.77.153