单例模式——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,因为它们是同一个实例
相关推荐
o0向阳而生0o1 天前
100、23种设计模式之适配器模式(9/23)
设计模式·适配器模式
将编程培养成爱好1 天前
C++ 设计模式《外卖菜单展示》
c++·设计模式
TechNomad1 天前
设计模式:状态模式(State Pattern)
设计模式·状态模式
努力也学不会java1 天前
【设计模式】 原型模式
java·设计模式·原型模式
TechNomad1 天前
设计模式:模板方法模式(Template Method Pattern)
设计模式·模板方法模式
leo03082 天前
7种流行Prompt设计模式详解:适用场景与最佳实践
设计模式·prompt
ytadpole2 天前
揭秘设计模式:工厂模式的五级进化之路
java·设计模式
烛阴2 天前
【TS 设计模式完全指南】用工厂方法模式打造你的“对象生产线”
javascript·设计模式·typescript
_请输入用户名2 天前
EventEmitter 是广播,Tapable 是流水线:聊聊它们的本质区别
前端·设计模式
Buling_02 天前
游戏中的设计模式——第一篇 设计模式简介
游戏·设计模式