• 单例模式,是一种常用的软件设计模式;

  • 单例模式就是确保一个类在任何情况下都只有一个实例,并提供一个全局访问点

类图

实现代码

class Singleton {
    private static instance: Singleton;

    // 私有构造函数防止外部实例化
    private constructor() {
        console.log('Singleton instance created');
    }

    // 全局访问点
    public static getInstance(): Singleton {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton();
        }
        return Singleton.instance;
    }

    // 业务方法
    public someBusinessLogic(): void {
        console.log('Executing business logic...');
    }
}

// 使用示例
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // true,两者是同一个实例
instance1.someBusinessLogic();

经典场景

jQuery

// 无论引入多少次 jQuery,都只会返回第一个 实例
if (window.jQuery != null) {
  return window.jQuery;
} else {
  //init~~~~~~~
}

模态窗口

class Login {
  constructor() {
    this.element = document.createElement('div');
    this.element.innerHTML = (
      `
        用户名 <input type="text"/>
        <button>登录</button>
      `
    );
    this.element.style.cssText = 'width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; display: block;';
    document.body.appendChild(this.element);
  }
  show() {
    this.element.style.display = 'block';
  }
  hide() {
    this.element.style.display = 'none';
  }
}

Login.getInstance = (function () {
  let instance;
  return function () {
    if (!instance) {
      instance = new Login();
    }
    return instance;
  }
})();

document.getElementById('showBtn').addEventListener('click', function (event) {
  Login.getInstance().show();
});
document.getElementById('hideBtn').addEventListener('click', function (event) {
  Login.getInstance().hide();
});
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

你好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 类图
  2. 2. 实现代码
  3. 3. 经典场景
    1. 3.1. jQuery
    2. 3.2. 模态窗口