mercredi 28 février 2018

Typescript : force classes to implement singleton pattern

Is there any way in forcing a class to implement singleton pattern in typescript. If so how ca i achieve this ?

So this is my interface and I would like that every class that implements it to be forced in implementing singleton

export interface ICorporationWebsitesService extends ISubject{
   readonly Instance: ICorporationWebsitesService;
}

export class CorporationWebsitesService implements ICorporationWebsitesService {

    private _instance: ICorporationWebsitesService;
    public get Instance(): ICorporationWebsitesService {
        if (this._instance === null) {
            this._instance = new CorporationWebsitesService();
        }
        return this._instance;
    }


    private constructor() {
    }
}

of course, i had to add the private constructor myself, but if someone else would like to implement this interface he/she is not required or noticed that the constructor should be made private.

Thank you.

Aucun commentaire:

Enregistrer un commentaire