单例模式——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,因为它们是同一个实例
相关推荐
庞轩px10 小时前
HotSpot详解——符号引用、句柄池、直接指针的终极解密
java·jvm·设计模式·内存·虚拟机·引用·klass
Yu_Lijing12 小时前
基于C++的《Head First设计模式》笔记——责任链模式
c++·笔记·设计模式·责任链模式
青木川崎14 小时前
设计模式之面试题
java·开发语言·设计模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——生成器模式
c++·笔记·设计模式
sg_knight2 天前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
吐个泡泡v2 天前
Python 开发“设计模式”指南
python·设计模式
程序员小寒2 天前
JavaScript设计模式(一):单例模式实现与应用
javascript·单例模式·设计模式
砍光二叉树2 天前
【设计模式】创建型-原型模式
设计模式·原型模式
helloworddm2 天前
第一篇:设计模式在 Android 视频播放器中的实战应用
android·设计模式·音视频