定义
保证一个类只有一个实例,并提供访问这个实例的接口。
代码实现
// 方式一:将这个实例放在类上class Singleton { static getInstance() { if (!Singleton.instance) { Singleton.instance = new Singleton(); } return Singleton.instance; }}
// 方式二:将这个实例放在闭包里class Singleton {}Singleton.getInstance = (function () { let instance = null; return function () { if (!instance) { instance = new Singleton(); } return instance; };})();
例子
tim-js-sdk
import TIM from 'tim-js-sdk';// 创建 SDK 实例,`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例const tim = TIM.create(options); // SDK 实例通常用 tim 表示