JavaScript设计模式之单例模式

什么是单例模式

单例模式规定只有一个实例,并且可以全局访问。需要时才创建类实例对象。

简单示例

ES5 简单实现

1
<!DOCTYPE html>
2
<html lang="en">
3
  <head>
4
    <meta charset="UTF-8" />
5
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
6
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
    <title>单例模式</title>
8
    <style>
9
      .overlay {
10
        z-index: 1000;
11
        position: fixed;
12
        top: 0;
13
        left: 0;
14
        right: 0;
15
        bottom: 0;
16
        height: 100%;
17
        background-color: rgba(0, 0, 0, 0.5);
18
        overflow: auto;
19
      }
20
      .message-box {
21
        width: 420px;
22
        background-color: #fff;
23
        border-radius: 4px;
24
        font-size: 18px;
25
        text-align: left;
26
        overflow: hidden;
27
        margin: auto;
28
        position: relative;
29
        top: 50%;
30
        transform: translateY(-50%);
31
      }
32
33
      .message-box-header {
34
        padding: 15px 15px 10px;
35
      }
36
      .message-box__title {
37
        padding-left: 0;
38
        margin-bottom: 0;
39
        font-size: 18px;
40
        line-height: 1;
41
        color: #303133;
42
      }
43
      .message-box_content {
44
        padding: 10px 15px;
45
        color: #606266;
46
        font-size: 14px;
47
      }
48
49
      .message-box__text p {
50
        margin: 0;
51
        line-height: 24px;
52
      }
53
      .message-box_btns {
54
        padding: 5px 15px 10px;
55
        text-align: right;
56
      }
57
58
      .button {
59
        color: #fff;
60
        background-color: #409eff;
61
        border-color: #409eff;
62
        border: none;
63
        padding: 9px 15px;
64
        font-size: 12px;
65
        border-radius: 3px;
66
        text-align: center;
67
        box-sizing: border-box;
68
        outline: none;
69
        margin: 0;
70
        white-space: nowrap;
71
        cursor: pointer;
72
      }
73
    </style>
74
  </head>
75
  <body>
76
    <button id="btn">点击打开 Message Box</button>
77
    <script>
78
      //  单例生成器
79
      var getSingleton = function (fn) {
80
        let instance;
81
        return function () {
82
          return instance || (instance = fn.apply(this, arguments));
83
        };
84
      };
85
      // 创建 MessageBox
86
      var createMessageBox = function (content, title, option) {
87
        let buttonText = option.buttonText || "ok";
88
        let callback = option.callback;
89
        let html = `<div class="message-box">
90
        <div class="message-box-header">
91
          <div class="message-box_title">
92
            <span>${title}</span>
93
          </div>
94
        </div>
95
        <div class="message-box_content">
96
          <div class="message-box_text">
97
            <p>${content}</p>
98
          </div>
99
        </div>
100
        <div class="message-box_btns">
101
          <button class="button" id="confirmBtn">${buttonText}</button>
102
        </div>
103
      </div>`;
104
105
        function confirm() {
106
          div.style.display = "none";
107
          callback("confirm");
108
        }
109
110
        var div = document.createElement("div");
111
        div.setAttribute("class", "overlay");
112
        div.innerHTML = html;
113
        div.style.display = "none";
114
        document.body.appendChild(div);
115
        document
116
          .getElementById("confirmBtn")
117
          .addEventListener("click", confirm);
118
        return div;
119
      };
120
      // 获取 MessageBox 实例
121
      var createSingleMessageBox = getSingleton(createMessageBox);
122
123
      document.getElementById("btn").addEventListener("click", function () {
124
        let MessageBox = createSingleMessageBox("这是一段内容", "标题名称", {
125
          buttonText: "确定",
126
          callback: (res) => {
127
            console.log(res);
128
          },
129
        });
130
        MessageBox.style.display = "block";
131
      });
132
    </script>
133
  </body>
134
</html>

ES6 通过 class 类来简单实现

1
class App{
2
    constructor(name,version){
3
        this.name = name;
4
        this.version = version;
5
    }
6
7
    static getInstance(name,version){
8
        if(!this.instance){
9
            this.instance = new App(name,version)
10
        }
11
        return this.instance;
12
    }
13
}
14
15
16
var app1 = App.getInstance('taobao',1)
17
var app2 = App.getInstance('jd',1)
18
19
console.log(app1 === app2);
20
console.log(app1);
21
console.log(app2);

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!