单例模式——javascript和typescript

概念

确保某个方法或者类只有一个是咧。而且自行实例子并向整个系统提供这个实例。

要点

  • 某个方法或类只能一个;
  • 必须自行创建这个实例
  • 必须自行向整个系统提供这个实例。

UML

instance Singleton - instance:Singleton -Singleton() +getInstance()

javascript 实现代码

javascript 复制代码
const Singleton = (function() {
  let instance;

  function createInstance() {
    // 在这里可以放一些初始化逻辑
    return {
      someMethod: function() {
        // 添加单例的方法和逻辑
      }
    };
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

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

console.log(instance1 === instance2); // 输出 true,因为它们是同一个实例

typescript 实现代码

typescript 复制代码
class Singleton {
  private static instance: Singleton | null = null;

  private constructor() {
    // 这里可以放一些初始化逻辑
  }

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Proxy(new Singleton(), {
        get: function(target, prop, receiver) {
          if (prop === 'instance') {
            return undefined; // 防止通过 instance 直接访问实例
          }
          return Reflect.get(target, prop, receiver);
        }
      });
    }
    return Singleton.instance as Singleton;
  }

  public someMethod() {
    // 在这里添加单例的方法和逻辑
  }
}

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

console.log(instance1 === instance2); // 输出 true,因为它们是同一个实例
相关推荐
choumin15 分钟前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式
37.2℃9951 小时前
Claude Design哪个公司技术好
python·设计模式
阿懂在掘金2 小时前
Vue 弹窗新范式——代码减少、复用翻倍与 AI 时代的前端基建
前端·设计模式·前端框架
choumin7 小时前
结构型模式——组合模式
c++·设计模式·组合模式·结构型模式
workflower7 小时前
供应链分销网络选址问题
人工智能·机器学习·设计模式·自然语言处理·机器人
第一个传播学1 天前
忍者龙剑传4豪华版下载及其玩法解析
设计模式
第一个传播学2 天前
赛博朋克2077修改器下载及其用法
设计模式
萧青山2 天前
2026国标合规:Agent Loop合规设计模式的6种循环架构(GB/Z 185.6+Python)
python·设计模式·agent loop·gb/z 185·国标合规
杨充3 天前
11.DDD与战术建模
设计模式·开源·代码规范
杨充3 天前
12.综合实战图片框架
设计模式·开源·代码规范