单例模式——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 小时前
设计模式(十二)结构型:享元模式详解
设计模式·系统架构·软考高级·享元模式
蝸牛ちゃん4 小时前
设计模式(十三)结构型:代理模式详解
设计模式·系统架构·代理模式·软考高级
贱贱的剑4 小时前
8. 状态模式
设计模式·状态模式
永卿00119 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式
使二颗心免于哀伤19 小时前
《设计模式之禅》笔记摘录 - 10.装饰模式
笔记·设计模式
Amagi.1 天前
Java设计模式-建造者模式
java·设计模式·建造者模式
源代码•宸2 天前
深入浅出设计模式——创建型模式之工厂模式
设计模式
天天进步20152 天前
设计模式在Java中的实际应用:单例、工厂与观察者模式详解
java·观察者模式·设计模式
尘似鹤2 天前
c++注意点(12)----设计模式(生成器)
c++·设计模式
归云鹤2 天前
设计模式十:单件模式 (Singleton Pattern)
单例模式·设计模式