class OnlyOne {
private static instance: OnlyOne;
private constructor(public name: string){}
static getInstance(){
if(!OnlyOne.instance){
OnlyOne.instance = new OnlyOne("The Only One");
}
return OnlyOne.instance;
}
}
let wrong = new OnlyOne('The Only One');
let right = OnlyOne.getInstance();
class OnlyOne {
private static instance: OnlyOne;
private constructor(public readonly name: string){}
static getInstance(){
if(!OnlyOne.instance){
OnlyOne.instance = new OnlyOne("The Only One");
}
return OnlyOne.instance;
}
}
let wrong = new OnlyOne('The Only One');
let right = OnlyOne.getInstance();
console.log(right.name) //Can access since it is a public property
right.name = 'Something else' //Able to change therefore
//TO ONLY SET THE PUBLIC AT THE CONSTRUCTOR ONLY AND NOT OTHER PLACE
//other than using just the getter keyword and do not specify the setter
//TS offer another easier way
//OR
class OnlyOne {
private static instance: OnlyOne;
public readonly name:string;
private constructor(name: string){
this.name = name;
}
static getInstance(){
if(!OnlyOne.instance){
OnlyOne.instance = new OnlyOne("The Only One");
}
return OnlyOne.instance;
}
}