美文网首页
JS设计模式--单例模式

JS设计模式--单例模式

作者: 勤奋的大鱼 | 来源:发表于2019-02-27 15:32 被阅读0次

    单例模式在js中的写法,十分简单,话不多说,上代码:

    let Store = function (name) {
      this.name = name
    }
    Store.prototype.getName = function () {
      return this.name
    }
    Store.getInstance = (function () {
      let instance = null
      return function (name) {
        if (!instance) {
          instance = new Store(name)
        }
        return instance
      }
    })()
    let store = Store.getInstance('car')
    let store2 = Store.getInstance('car2')
    console.log(store, store2, store === store2)
    

    透明单例

    let Store = (function () {
      let instance = null
      let Store = function (name) {
        if (instance) {
          return instance
        } else {
          this.name = name
          instance = this
          return instance
        }
      }
      Store.prototype.getName = function () {
        return this.name
      }
      return Store
    })()
    let store1 = new Store('car')
    let store2 = new Store('car2')
    console.log(store1, store2, store1 === store2)
    

    应用:

    1. 模态对话框
    2. 方法与组件库

    相关文章

      网友评论

          本文标题:JS设计模式--单例模式

          本文链接:https://www.haomeiwen.com/subject/vsqayqtx.html