单例模式——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,因为它们是同一个实例
相关推荐
wangmengxxw13 小时前
设计模式 -详解
开发语言·javascript·设计模式
进击的小头13 小时前
设计模式落地的避坑指南(C语言版)
c语言·开发语言·设计模式
短剑重铸之日13 小时前
《设计模式》第五篇:策略模式
java·后端·设计模式·策略模式
HL_风神15 小时前
C++设计模式学习-工厂方法模式
c++·学习·设计模式
琹箐15 小时前
设计模式——策略模式
设计模式·策略模式
YigAin1 天前
Unity23种设计模式之 命令模式
设计模式·命令模式
twj_one1 天前
java中23种设计模式
java·开发语言·设计模式
香芋Yu1 天前
【深度学习教程——01_深度基石(Foundation)】05_数据太多怎么吃?Mini-batch训练的设计模式
深度学习·设计模式·batch
进击的小头1 天前
设计模式组合应用:传感器数据采集与处理系统
c语言·设计模式
茶本无香2 天前
设计模式之十一—桥接模式:解耦抽象与实现的艺术
设计模式·桥接模式