JS 單例模式
概要:
單例指一個類只有一個實例,這個類自行創建這個實例。
利用對象字面量直接生成一個單例:
var singleton = { prop: 1, method: function(){ console.log(a); //1 }}
嚴格的說對象字面量可能不算單例模式,生成單例是對象字面量的作用(已經被封裝),而單例模式是一個設計模式(需要自行構思或設計)。
在類內部用new生成實例的單例模式:
var instance;var foo = function(){ if(!instance){ instance = new Singleton(); } return instance; function Singleton(){ this.name = 'single'; this.method = function(){ console.log(this.name); } };} var a = foo();var b = foo();a.method(); //singleconsole.log(a === b); //true
單例模式只要檢測一個實例是否被生成。假如沒有實例,則生成實例。假如已經生成則返回這個實例。保證這個類只有這一個實例。
由于hoisting,函數會提前聲明,所以 singleton 函數放在哪都沒所謂,但是每次調用都會聲明函數singleton,可能會不夠優雅。
由于new關鍵字是執行函數,同時this指向這個對象,所以可以判斷類的this是否賦值給instance:
var instance;var Singleton = function(){ if(instance){ return instance; } instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); }} var a = new Singleton();var b = new Singleton();a.method(); //singleconsole.log(a === b); //true
這個例子中,把instance指向了Singleton這個類,然后在類外部通過new來實例化,和上例中的new異曲同工。由于是通過修改this來達到檢測是否執行過Singleton類,所以個人感覺不夠語義化。
上面的例子用es6重構的寫法。
類內部new生成單例:
var instance;class foo{ static Singleton(){ if(!instance){ instance = new foo(); } return instance; } method(){ this.name = 'single'; console.log(this.name); }} var a = foo.Singleton();var b = foo.Singleton();a.method(); //singleconsole.log(a === b); //true
修改this指向生成單例:
var instance;class foo{ constructor(){ if(!instance){ this.Singleton(); } return instance; } Singleton(){ instance = this; this.name = 'single'; this.method = function(){ console.log(this.name); } }} var a = new foo();var b = new foo();a.method(); //singleconsole.log(a === b); //true
當然除了這兩種以外還有別的方式能實例化一個單例。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答