单例模式
class SingleTon {
// private 无法在外面实例化 new
private constructor() {}
// private 无法在外面获取
private static instance: SingleTon | null;
// 获取单例
static getInstance(): SingleTon {
if (SingleTon.instance === null) {
SingleTon.instance = new SingleTon();
}
return SingleTon.instance;
}
}
console.log(SingleTon.getInstance() === SingleTon.getInstance());
模块化 - commonjs ES6 Module
// getInstance.js 文件 - 开始
let instance
class Singleton {}
export default () => {
if (instance == null) {
instance = new Singleton
}
return instance
}
// getInstance.js 文件 - 结束