系統中被惟一使用
一個類只有一個實例javascript
public class SingleObject { // 私有化構造函數,外部不能new,只能內部new!!! private SingleObject() { } // 惟一被new出來的對象 private SingleObject instance = null // 獲取對象惟一的接口 public SingleObject getInstance() { if (instance == null) { // 只能new一次 instance = new SingleObject(); } return instance } // 對象方法 public void login(username, password) { System.out.println("login..,"); } } public class SingletonPatternDemo { public static void main(String[] args) { //不合法的構造函數 //編譯時報錯:構造函數SingleObject()不可見!!! //SingleObject object = new SingleObject(); //獲取惟一可用的對象 SingleObject object = SingleObject.getInstance(); object.login(); } }
class SingleObject { login() { console.log('login...') } } SingleObject.getInstance = (function () { let instance return function () { if (!instance) { instance = new SingleObject(); } return instance } })() // 沒法控制 let obj1 = SingleObject.getInstance() obj1.login() let obj2 = SingleObject.getInstance() obj2.login() console.log(obj1 === obj2) //------------------------------------------ let obj4 = SingleObject.getInstance() obj4.login() let obj5 = new SingleObject() obj5.login() console.log(obj4 === obj5)// false
//jQuery 只有一個 '$' if (window.jQuery != null) { return window.jQuer }else { //初始化...... }
class LoginForm { constructor() { this.state = 'hide' } show() { if (this.state === 'show') { alert('已經顯示') return } this.state = 'show' console.log('登陸框已顯示') } hide() { if (this.state === 'hide') { alert('已經隱藏') return } this.state = 'hide' console.log('登陸框已隱藏') } } LoginForm.getInstance = (function () { let instance return function () { if (!instance) { instance = new LoginForm(); } return instance } })() // 一個頁面中調用登陸框 let login1 = LoginForm.getInstance() login1.show() // login1.hide() // 另外一個頁面中調用登陸框 let login2 = LoginForm.getInstance() login2.show() // 二者是否相等 console.log('login1 === login2', login1 === login2)