单例模式——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,因为它们是同一个实例
相关推荐
贵慜_Derek8 分钟前
《从零实现 Agent 系统》连载 07|记忆系统:短期上下文 vs 长期外部记忆
人工智能·设计模式·架构
老码观察5 小时前
设计模式实战解读(一):单例模式——全局唯一实例的正确打开方式
单例模式·设计模式
老码观察5 小时前
设计模式实战解读(二):工厂模式——对象创建的解耦艺术
设计模式·log4j
看山是山_Lau7 小时前
原型模式:当复制比重新创建更高效时
设计模式·原型模式
用户356302904877 小时前
【设计模式】观察者模式——事件通知机制
设计模式
追烽少年x8 小时前
STL中的设计模式(二)
c++·设计模式
悟05158 小时前
设计模式-模板模式
设计模式
BLSxiaopanlaile8 小时前
有关创建型的几个设计模式总结
设计模式
蜡笔小马9 小时前
14.C++设计模式-状态模式
c++·设计模式·状态模式
加油201910 小时前
嵌入式软件技术栈和学习路线详解
linux·arm开发·数据结构·mqtt·设计模式·嵌入式