Skip to content

[javascript] Singleton 唯一實體

Published: at 09:38 AM (2 min read)

最近跟同事討論到了 Singleton 的實作,之前都沒有想過實際的細部實作

要創造一個物件,我們可以使用物件或 new 方法,以下我會分別介紹這兩種方法如何實作 Singleton。


物件:

[javascript]

var myInstance = { attr: ‘123’, method1: function() { console.log(‘method1’); }, method2: function() { console.log(‘method2’); } };

var a = myInstance; var b = myInstance;

a.attr = ‘456’;

console.log(a === b); // true console.log(a.attr); // ‘456’ console.log(b.attr); // ‘456’ myInstance.attr = ‘789’; console.log(a.attr); // ‘789’ console.log(b.attr); // ‘789’ [/javascript]

上面這段程式碼 a 和 b 將會是相同實體。

new 方法建造物件:

[javascript]

function myInstance(){

if(myInstance.instance){ return myInstance.instance; }

this.attr = ‘123’;

myInstance.instance = this; };

var a = new myInstance(); var b = new myInstance();

console.log(a === b); // true console.log(a.attr); // ‘123’ console.log(b.attr); // ‘123’ a.attr = ‘456’; console.log(a.attr); // ‘456’ console.log(b.attr); // ‘456’ [/javascript]

利用這個 myInstance 物件(函式)的靜態變數 (instance) 記住已經建造過的物件,讓之後建造時都回傳先前已存在之物件。

[javascript] var myInstance;

function myInstance(){ var instance = this;

this.attr = ‘123’;

myInstance = function(){ return instance; }; };

var a = new myInstance(); var b = new myInstance();

console.log(a === b); // true console.log(a.attr); // ‘123’ console.log(b.attr); // ‘123’ a.attr = ‘456’; console.log(a.attr); // ‘456’ console.log(b.attr); // ‘456’ [/javascript]

這段程式碼則是另一種 new 方法的 Singleton 的實作方法,第一次進函式時,覆寫 myInstance 的 constructor,之後 new myInstance() 時,其實只會 return instance。

參考資料:

http://stackoverflow.com/questions/1479319/simplest-cleanest-way-to-implement-singleton-in-javascript

http://stackoverflow.com/questions/31222765/javascript-singleton-pattern

http://cythilya.blogspot.tw/2015/06/javascript-design-pattern-singleton.html