// 获取实例对象 var getInstance = (function() { var instance = null; returnfunction(name) { if(!instance) { instance = new Singleton(name); } return instance; } })();
// 测试单例模式的实例 var a = getInstance("aa"); var b = getInstance("bb"); console.log(b.getName()); // "aa" console.log(a === b); // true
封装一个获取实例的模块
1 2 3 4 5 6 7
// 获取实例的封装代码 var getInstance = function(fn) { var result; returnfunction(){ return result || (result = fn.call(this,arguments)); } };
ES5实现,封装一个函数,作为一个对象返回,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
functionStorageSingleton () {} StorageSingleton.prototype.getItem = function (key){ return localStorage.getItem(key) } StorageSingleton.prototype.setItem = function (key, value) { return localStorage.setItem(key, value) }
var Storage = (function(){ var instance returnfunction(){ return instance || instance = new StorageSingleton() } })() var a = new Storage() var b = new Storage() a === b // true a.setItem('a','a') b.getItem('a') // 'a'
ES6原生加入了class的语法糖,这样的写法和其他语言的类构造方法相似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classStorage{ constructor(){ if(!Storage.instance){ Storage.instance = this } return Storage.instance } getItem (key) { return localStorage.getItem(key) } setItem (key, value) { return localStorage.setItem(key, value) } } let a = new Storage() let b = new Storage() a === b // true a.setItem('a','a') b.getItem('a') // 'a'