首页 > 其他分享 >【ES6】使用Proxy实现单例模式

【ES6】使用Proxy实现单例模式

时间:2024-08-30 17:50:44浏览次数:7  
标签:ES6 p1 const ins Person SingletonPerson Proxy 单例 new

前言

由于JS没有private关键字,无法私有化构造器,所以下面代码无法限制:

class Person {
  constructor() {
    console.log("Person created");
  }
}

const p1 = new Person();
const p2 = new Person();

console.log(p1 === p2); // false

在这里插入图片描述

实现

通过 Person.getInstance() 生成对象

class Person {
  constructor() {
    console.log("Person created");
  }
  static _ins = null
  static getInstance() {
    if (!this._ins) {
      this._ins = new Person();
    }
    return this._ins;
  }
}

const p1 = Person.getInstance();
const p2 = Person.getInstance();

console.log(p1 === p2);

在这里插入图片描述

但是如果创建对象时使用new Person(),仍无法实现单例模式。

下面封装一个函数,把任何类传入,将其变为单例模式:

function singleton(className) {
  let ins
  return class {
    constructor(...args) {
      if (!ins) {
        ins = new className(...args)
      }
      return ins
    }
  }
}
class Person {
  constructor() {
    console.log("Person created");
  }
}

// const p1 = new Person();
// const p2 = new Person();
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();

console.log(p1 === p2);

在这里插入图片描述

但是这种实现方式仍有缺陷,并不能添加原型方法

const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();

在这里插入图片描述

下面使用 Proxy 实现,不返回一个新类,而是代理,给代理对象的原型上加方法等于直接给该对象的原型加方法。

function singleton(className) {
  let ins
  return new Proxy(className, {
    construct(target, args) {
      if (!ins) {
        ins = new target(...args);
      }
      return ins
    }
  })
}
class Person {
  constructor() {
    console.log("Person created");
  }
}
const SingletonPerson = singleton(Person);
const p1 = new SingletonPerson();
const p2 = new SingletonPerson();
SingletonPerson.prototype.say = function () {
  console.log("hello world");
}
p1.say();
console.log(p1 === p2);

在这里插入图片描述

标签:ES6,p1,const,ins,Person,SingletonPerson,Proxy,单例,new
From: https://blog.csdn.net/owo_ovo/article/details/141724153

相关文章

  • ES6迭代器协议
    迭代协议参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols 作为ECMAScript2015的一组补充规范,迭代协议并不是新的内置实现或语法,而是协议。这些协议可以被任何遵循某些约定的对象来实现。 迭代协议具体分为两个协议:可迭代协议......
  • day15JS-es6的基础语法
     1.严格模式1.1严格模式的使用方法使用方法1:"usestrict";开启严格模式。使用方法2:<scripttype="moaule"></script> 当设置script标签为模块化时,自动启用严格模式。 1.2严格模式的限制1. 要求变量不能重名。//报错"usestrict";vara=2;vara=4; 2.......
  • ES6两个数组进行比较
    在ES6中,可以使用扩展运算符...和Array.prototype.includes方法来比较两个数组,并找出它们的不同元素。constarray1=[1,2,3,4,5];constarray2=[3,4,5,6,7];//找出在array1中而不在array2中的元素constdiff1=array1.filter(item=>!array2.includes(item));//......
  • sqlsugar 封装 单例模式 多数据库
    #PlayGround\.config\dotnet-tools.json{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"0.29.1","commands":["dotnet-csharpi......
  • sqlsugar 单例模式 封装
    usingSystem.Linq.Expressions;usingMicrosoft.Extensions.Configuration;usingSqlSugar;namespaceSqlSugarFrameworkCore;publicclassDbSettings{publicconststringAppOne="AppOne";publicconststringAppDevOne="AppDevOne";pub......
  • 13.JS学习篇-ES6 React 项目模板
    1.项目能力支持1.项目初始化脚手架1.前端编码规范工程化(lint工具、NodeCLI等)2.用工具提升项目的编码规范,如:eslint、stylelint、commitlint、markdownlint、husky等3.工具对于JavaScript、Typescript、React、Vue等不同类型的前端项目下的标准的语法限制;2.相关基础功能......
  • 【设计模式】单例模式(线程安全)
     ......
  • JavaScript 模块化开发:ES6 模块与 CommonJS 的对比与应用
    ​​您好,我是程序员小羊!前言随着前端项目规模的增长,代码组织和管理变得越来越复杂。模块化开发成为解决这一问题的有效手段,能够帮助开发者将代码进行分割、复用和维护。JavaScript在发展过程中出现了多种模块化规范,其中最为广泛使用的有ES6模块(也称为ESModules)......
  • 单例模式 lock 多线程 双重检查锁定机制
    单例模式单例模式publicclassSingleton{//定义一个静态变量来保存类的实例privatestaticSingletonuniqueInstance;//定义一个标识确保线程同步privatestaticreadonlyobjectlocker=newobject();//定义私有构造函数,使外界不能创建该类......
  • Proxyless的多活流量和微服务治理
    1.引言1.1项目的背景及意义在当今的微服务架构中,应用程序通常被拆分成多个独立的服务,这些服务通过网络进行通信。这种架构的优势在于可以提高系统的可扩展性和灵活性,但也带来了新的挑战,比如:服务间通信的复杂性:不同服务之间需要进行可靠的通信,处理失败重试、负载均衡等问题。......