定义

在一个程序中,该类只创建一个实例对象。

类图

Snipaste_2020-09-13_20-51-34.png

代码

基本的单例模式

  1. class Window {
  2. private static instance: Window;
  3. private constructor() {}
  4. static getInstance() {
  5. if (!Window.instance) {
  6. Window.instance = new Window();
  7. }
  8. return Window.instance;
  9. }
  10. }
  11. let w1 = Window.getInstance();
  12. let w2 = Window.getInstance();
  13. console.log(w1 === w2);

单例与构建过程分离

  1. function Window() {}
  2. let createInstance = (function () {
  3. let instance: Window;
  4. return function () {
  5. if (!instance) {
  6. instance = new Window();
  7. }
  8. return instance;
  9. };
  10. })();
  11. let w1 = createInstance();
  12. let w2 = createInstance();
  13. console.log(w1 === w2);

封装变化,可以创建任何类型实例

  1. function Window() {}
  2. function Modal() {}
  3. let createInstance = function (Constructor: any) {
  4. let instance: any;
  5. return function (this: any) {
  6. if (!instance) {
  7. Constructor.apply(this, arguments);
  8. Object.setPrototypeOf(this, Constructor.prototype);
  9. instance = this;
  10. }
  11. return instance;
  12. };
  13. };
  14. let createWindow = createInstance(Window);
  15. let createModal = createInstance(Modal);
  16. let w2 = new (createWindow as any)();
  17. let w1 = new (createWindow as any)();
  18. let m1 = new (createModal as any)();
  19. let m2 = new (createModal as any)();
  20. console.log(w1 === w2);
  21. console.log(m1 === m2);

模态框实例

  1. <button id="show">显示窗口</button>
  2. <button id="hide">隐藏窗口</button>
  3. <script>
  4. class LoginModal {
  5. static instance
  6. constructor(id) {
  7. this._element = document.createElement("div")
  8. this._element.innerHTML = `
  9. <form>用户名<input /><button type='submit'>提交</button></form>
  10. `
  11. this._element.style.cssText = 'border-radius:10px;border:3px solid #333;width:200px;height:100px;position: absolute;top:45%;left:45%;'
  12. document.body.appendChild(this._element)
  13. }
  14. show() {
  15. this._element.style.display = "block"
  16. }
  17. hide() {
  18. this._element.style.display = 'none'
  19. }
  20. static getInstance() {
  21. if (!LoginModal.instance) {
  22. LoginModal.instance = new LoginModal()
  23. }
  24. return LoginModal.instance
  25. }
  26. }
  27. document.getElementById("show").addEventListener("click", function () {
  28. LoginModal.getInstance().show()
  29. })
  30. document.getElementById("hide").addEventListener("click", function () {
  31. LoginModal.getInstance().hide()
  32. })

服务端使用缓存cache

  1. let express = require("express");
  2. let app = express();
  3. let fs = require("fs");
  4. // 缓存一定要写成单例
  5. let cache = {};
  6. app.get("/api/users/:id", function (req, res) {
  7. let id = req.params.id;
  8. if (cache[id]) {
  9. res.json(cache[id]);
  10. } else {
  11. fs.readFile(`./users/${id}.json`, "utf8", (err, data) => {
  12. let user = JSON.parse(data);
  13. res.json(user);
  14. });
  15. }
  16. });