前言
单例模式
指一个类有且仅有一个实例,并提供一个访问它的全局访问点。
实现
定义私有构造函数,即 private constructor
,禁止使用 new
关键字生成实例。
Constructor of class 'Dep' is private and only accessible within the class declaration.
// app.ts
class Dep {
private static instance: Dep;
private constructor(id: string) {}
static getInstance() {
// 静态方法中可以使用 this.静态属性,或者Dep.静态属性。
if (this.instance) {
return this.instance;
}
this.instance = new Dep("AAA");
return this.instance;
}
}
const dep1 = Dep.getInstance();
const dep2 = Dep.getInstance();
console.log(dep1 === dep2);
将 app.ts
编译成 es2016
版的 app.js
// app.js
"use strict";
class Dep {
constructor(id) { }
static getInstance() {
// 静态方法中可以使用 this.静态属性,或者Dep.静态属性。
if (this.instance) {
return this.instance;
}
this.instance = new Dep("AAA");
return this.instance;
}
}
const dep1 = Dep.getInstance();
const dep2 = Dep.getInstance();
console.log(dep1 === dep2);