单例模式——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,因为它们是同一个实例
相关推荐
码匠许师傅4 小时前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml
小程故事多_808 小时前
从快速迭代到稳定存续,Google五大设计模式重构长效AI智能体落地逻辑
人工智能·设计模式·重构
码匠许师傅21 小时前
【设计模式精讲】22.中介者模式(Mediator)
c++·设计模式·软件工程·uml·中介者模式
2401_868534781 天前
网规备考_2.4 路由协议
c++·设计模式
cpp_learner1 天前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
码匠许师傅1 天前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
新知图书2 天前
第8章 多智能体协同
人工智能·设计模式·智能体
京师20万禁军教头2 天前
39面向对象(高级)-设计模式
java·开发语言·设计模式
新知图书2 天前
3.5 智能体设计模式1:反应式智能体与自动导航案例
人工智能·设计模式·智能体
码匠许师傅2 天前
【设计模式精讲】21.迭代器模式(Iterator)
c++·设计模式·rpc·迭代器模式·软件工程·uml