Javascript design pattern system explanation and application——study notes 3-singleton pattern

Singleton mode

  • Used only in the system
  • There is only one instance of a class

Example

  • Login box
  • shopping cart

note:

  • Singleton mode needs to use java features (private)
  • Not in ES6 (except for typescript)
  • Only java code can be used to demonstrate the content of UML diagrams

Java code demonstration:

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();
  }
}

JS uses singleton mode

class SingleObject {
    
    
  login() {
    
    
    console.log('login...')
  }
}

SingleObject.getInstance = (funciton () {
    
    
  let instance
  return function () {
    
    
    if (!instance) {
    
    
      instance = new SingleObject()
    }
    return instance
  }
})()

// 测试:注意这里只能使用静态函数getInstance, 不能使用new SingleObject()。 只能靠文档约束
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log(obj1 === obj2)  // true  两者完全相等
let obj3 = new SingleObject()  // 无法完全控制
obj3.login()
console.log(obj1 === obj3) // false

Scenes

  • jQueryonly one$
  • Mock login box
  • other

jQueryonly one$

// jQuery只有一个$
if (window.jQuery != null) {
    
    
  return window.jQuery
} else {
    
    
  // 初始化。。。
}

Mock login box

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 funciton (0 {
    
    
    if (!instance) {
    
    
      instance = new LoginForm()
    }
    return instance
  })
})()

other

  • Shopping cart (similar to login box)
  • Store in vuex and redux

Design principle verification

  • Comply with the single responsibility principle, only instantiate the only object
  • There is no specific open and closed principle, but it absolutely does not violate the open and closed principle

Guess you like

Origin blog.csdn.net/weixin_40693643/article/details/108820225