Use cases for a non-public constructor

A private constructor revokes the possibility to instantiate the class from the outside. The following code does not compile because the constructor is private. The same would also be true if the constructor were protected:

class PrivateConstructor{
private constructor(){
}
}

const pc = new PrivateConstructor(); // Does not compile

In that case, the only way to instantiate the class is by using a public static function that creates the object of the type class and returns it. In the following code, the private constructor creates an instance; to access this instance, GetInstance is used, which is static and does not need to have an instance to be called:

class SingletonClass {
private static instance: SingletonClass;
private constructor() {
SingletonClass.instance = new SingletonClass();
}

public static GetInstance(): SingletonClass {
return SingletonClass.instance;
}
}
const singletonClass = SingletonClass.GetInstance();

A known pattern is to have a SingletonClass. Only a single instance of the class exists and this control can be managed by having a single function that uses new once and then always returns the same instance. Another use case is to have a factory that creates all the instances.

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

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