饿汉式在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变,所以天生是线程安全的。
export class XmlService {
private static _instance:XmlService = new XmlService();
constructor() {
winston.info(“init XmlService”);
if (XmlService._instance) {
throw new Error(“Error: Instantiation failed: Use getInstance() instead of new.”);
}
XmlService._instance = this;
}
public static getInstance(): XmlService {
return XmlService._instance;
}
}
Nodejs项目中用到的单例模式
最新推荐文章于 2022-09-06 14:52:34 发布