typescript TypeScript Private Constructos和Singletons

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript TypeScript Private Constructos和Singletons相关的知识,希望对你有一定的参考价值。

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;
	}
}

以上是关于typescript TypeScript Private Constructos和Singletons的主要内容,如果未能解决你的问题,请参考以下文章

typescript TypeScript Snippets #typescript

TypeScript入门五:TypeScript的接口

TypeScript系列教程--初探TypeScript

TypeScript入门三:TypeScript函数类型

typescript使用 TypeScript 开发 Vue 组件

认识 TypeScript