简体   繁体   中英

Should I be using a Class or an Object Literal when implementing a singleton in JS?

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.

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:

  1. Private a protected methods/members.
  2. Inheritance. If you need to define a similar object you can extend and super your way into it very quickly and easily.
  3. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM