单例模式——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,因为它们是同一个实例
相关推荐
L***p3138 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
MC丶科10 小时前
Java设计模式漫画英雄宇宙-观察者模式 —— Watcher女侠与“消息广播网”!
观察者模式·设计模式
stormsha11 小时前
Java 设计模式探秘饿汉式与懒汉式单例模式的深度解析
java·单例模式·设计模式·java-ee
f***453211 小时前
Spring Boot 经典九设计模式全览
java·spring boot·设计模式
口袋物联17 小时前
设计模式之单例模式在 C 语言中的应用(含 Linux 内核实例)
c语言·单例模式·设计模式
__万波__17 小时前
二十三种设计模式(一)--单例模式
java·单例模式·设计模式
雨中飘荡的记忆20 小时前
设计模式之组合模式
java·设计模式
Blossom.11820 小时前
基于Mamba-2的实时销量预测系统:如何用选择性状态空间干掉Transformer的O(n²)噩梦
人工智能·python·深度学习·react.js·机器学习·设计模式·transformer
一个处女座的暖男程序猿21 小时前
3大类设计模式
设计模式
双木的木21 小时前
Coggle数据科学 | 并行智能体:洞察复杂系统的 14 种并发设计模式
运维·人工智能·python·设计模式·chatgpt·自动化·音视频