jeudi 14 mars 2019

Extending a Singleton Class in TypeScript

I'm trying to Extend and override a method in a Singleton Class in TypeScript, here's the code for the Singleton Class:

class Singleton {
    protected static _instance: Singleton;

    protected constructor() { }

    public static get instance() {
        if (Singleton._instance === undefined) {
            Singleton._instance = new Singleton();
        }

        return Singleton._instance;
    }

    public doWork() {
        console.log('doing work in singleton...');
    }
}

ExtendedSingleton Class:

class ExtendedSingleton extends Singleton {
    protected static _instance: ExtendedSingleton;

    protected constructor() {
        super();
    }

    public static get instance() {
        console.log('Creating Extended Singleton');
        if (ExtendedSingleton._instance === undefined) {
            ExtendedSingleton._instance = new ExtendedSingleton();
        }

        return ExtendedSingleton._instance;
    }

    public doWork() {
        console.log('doing work in extended singleton...');
    }
}

Finally the code that runs both classes:

Singleton.instance.doWork();
ExtendedSingleton.instance.doWork();

The problem is that both logs 'doing work in singleton...', and when I swap the lines the problem is fixed. I don't know why this behavior happens (I think it's mostly something I'm not aware of on how javascript's inheritance works), or if there's a better solution to my problem.

Note: I fixed the problem by using an interface and implementing it in both classes, but this won't be efficient in a large class where I need to override a method or two only.

Aucun commentaire:

Enregistrer un commentaire