單例模式:
- 要求一個類只有一個實例化對象存在
- 這個實例化對象必須提供一個全局對外訪問方式
- 這個實例化對象應當是私有的,不能被外界直接訪問或者更改
方式1 get實現
- 唯一實例化:判斷這個對象是否存在,如果存在就返回,不再創建
- 全局訪問:靜態
- 私有:get只讀,沒有set,只讀不寫
export default class Model3 { constructor() { } static get instance() { if (!Model3._instance) { Object.defineProperty(Model3, "_instance", { value: new Model3() }); } return Model3._instance; } }
方式2 閉包實現
- 唯一實例化:如果存在,返回存在,不再新建
- 全局訪問:返回一個class,class內設置靜態方法getInstance
- 私有:通過閉包實現,外部函數設置變量,內部調用這個變量
export default (function(){ var _instance; return class Model1{ static getInstance(){ if(!_instance) _instance = new Model1(); return _instance; } } })();