单例模式——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,因为它们是同一个实例
相关推荐
桦说编程1 天前
Guava 迭代器增强类介绍
java·后端·设计模式
李宥小哥1 天前
创建型设计模式1
stm32·嵌入式硬件·设计模式
李宥小哥1 天前
结构型设计模式2
网络·数据库·设计模式
guangzan1 天前
TypeScript 中的策略模式
设计模式
乐悠小码2 天前
Java设计模式精讲---04原型模式
java·设计模式·原型模式
李宥小哥2 天前
行为型设计模式2
windows·设计模式
Juchecar2 天前
Java示例:设计模式是如何在实战中“自然生长”出来
java·设计模式
Juchecar2 天前
超越经典23种设计模式:新模式、反模式与函数式编程
设计模式·云原生·函数式编程
Juchecar2 天前
设计模式不是Java专属,其他语言的使用方法
java·python·设计模式