說明:只要實例化一次,超過一次的實例化過程會返回以前實例化的結果,而不會在內存中再次寫入新的實例對象。----相似於once。javascript
須要遵照的原則:「單一職責的原則」,每個類或者函數只負責一個功能。html
最佳實踐:使用代理方式實現單例模式,使用一個代理函數來實現實單例例化java
/* 摘自《JavaScript設計模式與開發實踐》 */ var CreateDiv = function( html ){ this.html = html; this.init(); }; CreateDiv.prototype.init = function(){ var div = document.createElement( 'div' ); div.innerHTML = this.html; document.body.appendChild( div ); }; // 下來代理類 proxySingletonCreateDiv var ProxySingletonCreateDiv = (function(){ var instance; return function( html ){ if ( !instance ){ instance = new CreateDiv( html ); } return instance; } })(); // 測試函數 var a = new ProxySingletonCreateDiv( 'sven1' ); var b = new ProxySingletonCreateDiv( 'sven2' ); alert( a === b ); //返回true
class Singleton{ name:string; constructor(name:string){ this.name = name; this.init(); } private init() { console.log("已建立"); } } class ProxySingleton{ protected static instance:any = null; constructor(public name:string){ if( !ProxySingleton.instance ){ ProxySingleton.instance = new Singleton(this.name); } return ProxySingleton.instance; } } // test let a = new ProxySingleton("張三"); let b = new ProxySingleton("李四"); console.log(a===b); //返回true