美文网首页
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设计模式一:工厂模式jS设计模式二:单例模式JS设计模式三:模块模式JS设计模式四:代理模式JS设计模式五:职...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • js的4种设计模式及Vue小结(1)

    4种js设计模式 模块模式(module) 原型模式(prototype) 观察者模式(observer) 单例模...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 十道前端面试题第【05】篇

    摘要:本篇是设计模式专题,分享了10个设计模式的JS示例代码——工厂模式、单例模式、原型模式、建造者模式、外观模式...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

网友评论

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

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