I often find myself needing to use a singleton based pattern when creating web apps with typescript and react. Previously I have always implemented these with object literals like so:
interface IExample {
var_one: string;
var_two: boolean;
func_one: () => void;
func_two: () => void;
}
const Example:IExample = {
var_one: "",
var_two: false,
func_one() {
return;
},
func_two() {
return;
}
}
I would much prefer to use a class based system but am wondering if there are any downsides to this or what are the pros and cons of each. An example would be:
class ExampleClass
{
private static _instance:ExampleClass = new ExampleClass();
constructor() {
if(ExampleClass._instance){
throw new Error("Instance already created");
}
ExampleClass._instance = this;
}
}
I have previously only really used the object literal pattern in my code but would much prefer to use the class based system if there is little difference between the two.
CodePudding user response:
I would agree with preferring to use a Class. I can think of a few distinct advantages that Classes offer that using pojo don't:
- Private a protected methods/members.
- Inheritance. If you need to define a similar object you can
extend
andsuper
your way into it very quickly and easily. - Simpler syntax for
object factory
behavior.
I would say that the more complex you plan on making it- the more obvious a choice a Class becomes. In javascript- nearly everything is already an Object and Classes just add a couple shortcuts. The only advantage using a pojo would give is simplicity in syntax.
CodePudding user response:
You might be interested to learn that modules are already singletons, so you can leverage the module system to achieve what you need.
export class MyClass {
constructor(readonly foo: string) {}
}
export const instance = new MyClass("bar");
In your consuming modules, you can import either the class, or your singleton instance.
import { instance } from "./lib";
instance.foo // bar