理解js設計模式之單例模式
阿新 • • 發佈:2017-08-15
單例 false single 這樣的 字面量 不可靠 urn 如果 ==
單例模式的定義:只提供唯一的一個實例來讓你訪問
js中單例是天然存在的:
var a1={ hello:‘js‘ } var a2={ hello:‘js‘ } console.log(a1===a2) //false
任意生成的一個對象字面量其實就是一個對象而且他也是唯一的,對象字面量聲明對象的方式,每次都會在對內存中創建一個新的空間,所以不管你對象裏面的東西一不一樣,他們就是不一樣的(本質是地址不一樣)
但是這樣的單例是不可靠的,很容易被覆蓋。。。你將a1,a2賦一個新的值,之前的單例對象就被垃圾回收了
如何生成可靠的單例? 用js的閉包可以很容易的做到這一點
var Singleton=function(name){ this.name=name; } Singleton.prototype.getName=function(){ return this.name; } Singleton.getInstance=(function(){ var instance=null; return function(name){ if(!instance) return instance=new Singleton(name); return instance; } })() var one=Singleton.getInstance(‘I am first one‘); var two=Singleton.getInstance(‘I am second one‘); console.log(one===two); //true console.log(one); console.log(two);
這樣就完成了一個簡單的單例模式,書上將這種寫法稱為 ‘不透明’ 的單例模式,因為生成一個單例要通過 Singleton.getInstance 這個方法來獲得,不能像正常創建對象那樣,也就是new Singleton() 這樣,這種稱為 ‘透明’ 的單例模式;
然而,其實單例模式的實現方式上:就是維護一個可訪問的變量,來標誌是否已經生成了一個實例了,如果生成了就將他返回,沒有生成就創建一個,保存起來
那麽,閉包的優勢又體現出來了:
var Singleton=(function(){ var instance=null; function SingletonHelper(name){ if(instance) return instance; this.name=name; return instance=this; //將第一個new 產生的對象保存在instance 下一個new 要去生成的時候就會返回這個實例 } SingletonHelper.prototype.getName=function(){ return this.name; } return SingletonHelper; })() var one=new Singleton(‘I am first one‘); var two= new Singleton(‘I am second one‘); console.log(one); console.log(two); console.log(one===two);
這樣就可以正常的去new 一些對象,而且不管你new 幾個,結果都是一樣的,都是第一個生成的那個對象
理解js設計模式之單例模式