单例模式——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,因为它们是同一个实例
相关推荐
Zane199412 小时前
同一段单例代码,为什么在高并发下偶尔会创建出两个实例?聊聊哪种单例实现才是真的安全
设计模式
Carl_奕然12 小时前
【智能体】Loop 的四种设计模式之:Agent Loop(2026 最新版)
人工智能·设计模式·语言模型
小酒星小杜13 小时前
画 AI 漫画,别只会写“日漫风”:10 种画风、适用故事和可复制提示词
人工智能·设计模式·程序员
sarasuki1 天前
为什么 Agent 工具需要一个「协议」而不是「框架」:MCP 成为标准的底层逻辑
设计模式·agent·mcp
vivo互联网技术1 天前
知识不是文件,也不是向量 | KDC 系列 02
人工智能·设计模式·架构
Zane19947 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫8 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19948 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19949 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..9 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot