JavaScript-Typescript Design Patterns: Singleton and private constructors

What is a singleton?

// BASE CLASS
class Department {
protected employee: string[] = []; constructor(public name: string, protected id: string) { this.name = name; } describe() { console.log(` DEPARTMENT: ${this.name} ID: ${this.id} `); }}// CHILD CLASS:
class AccountDepartment extends Department {
admin: string []; private static instance: AccountDepartment; // initialize a static variable // Cannot be accessed from outside the class
private constructor(id: string, admin: string[]) {
super(id, 'Account'); this.admin = admin; this.id = id; } // Always return the same instance
static getInstance () {
if(AccountDepartment.instance) { // i.e. classname.variable return this.instance; } return this.instance = new AccountDepartmntt('d25', ['Max']); }}// So here only once instance is used - despite calling multiple timesconst account = AccountDepartmntt.getInstance();console.log(account);const account2 = AccountDepartmntt.getInstance();console.log(account2);// const accountingDepartmenttAC = new AccountDepartmntt('d12', ['Rana']);
Getting same o/p for different instance
var UserStore = (function(){
var _data = [];

function add(item){
_data.push(item);
}

function get(id){
return _data.find((d) => {
return d.id === id;
});
}

return {
add: add,
get: get
};
}());
const _data = [];

const UserStore = {
add: item => _data.push(item),
get: id => _data.find(d => d.id === id)
}

Object.freeze(UserStore);
export default UserStore;
class UserStore {
constructor(){
this._data = [];
}

add(item){
this._data.push(item);
}

get(id){
return this._data.find(d => d.id === id);
}
}

const instance = new UserStore();
Object.freeze(instance);

export default instance;
class UserStore {
constructor(){
if(! UserStore.instance){
this._data = [];
UserStore.instance = this;
}

return UserStore.instance;
}

//rest is the same code as preceding example

}

const instance = new UserStore();
Object.freeze(instance);

export default instance;

Closing thoughts:

Web Artisan. Human — Engineering

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store