秋雨
首页
  • HTML
  • CSS
  • JavaScript
设计模式
webpack
  • 前端常识
  • ES
  • React
  • Redux
  • ReactRouter
  • 事件循环
  • 浏览器渲染流程
  • Vue项目性能优化
  • Vue
  • App
Github
首页
  • HTML
  • CSS
  • JavaScript
设计模式
webpack
  • 前端常识
  • ES
  • React
  • Redux
  • ReactRouter
  • 事件循环
  • 浏览器渲染流程
  • Vue项目性能优化
  • Vue
  • App
Github
  • 构造器模式
  • 原型链模式
  • 工厂模式
  • 抽象工厂模式
  • 建造者模式
  • 单例模式
  • 装饰器模式
  • 适配器模式
  • 适配器模式
  • 代理模式
  • 观察者模式
  • 发布订阅模式
  • 模块模式
  • 桥接模式
  • 组合模式
  • 命令模式
  • 命令模式
  • 迭代器模式
  • 职责链模式

简介

  • 保证一个类仅有一个实例,并提供一个访问它的全局访问点。
  • 主要解决一个全局使用的类频繁的创建和销毁,占用内存。

闭包形式

var Singleton = function () {
  var instance;
  function User(name, age) {
    this.name = name;
    this.age = age;
  }
  return function (name, age) {
    if (!instance) {
      instance = new User(name, age);
    }
    return instance;
  };
};

ES6

class Singleton {
  constructor(name, age) {
    if (!Singleton.instance) {
      this.name = name;
      this.age = age;
      Singleton.instance = instance;
    }
    return Singleton.instance;
  }
}

示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .kerwin-modal {
        position: fixed;
        width: 200px;
        height: 200px;
        line-height: 200px;
        text-align: center;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <!-- <div class="kerwin-modal">登陆对话框</div> -->

    <button id="open">打开</button>
    <button id="close">关闭</button>
    <script>
      const Modal = (function () {
        const instance = null;
        if (!instance) {
          instance = document.createElement("div");
          instance.innerHTML = "登陆对话框";
          instance.className = "kerwin-modal";
          instance.style.display = "none";
          document.body.appendChild(instance);
        }
        return instance;
      })();
      document.querySelector("#open").onclick = () => {
        //创建modal
        const modal = Modal();
        modal.style.display = "block";
      };
      document.querySelector("#close").onclick = () => {
        //创建modal
        const modal = Modal();
        modal.style.display = "none";
      };
    </script>
  </body>
</html>
最后更新:
贡献者: Mrlishizhen
Prev
建造者模式
Next
装饰器模式