首页 > 编程语言 >[Javascript] Singleton Pattern

[Javascript] Singleton Pattern

时间:2022-08-26 15:57:52浏览次数:101  
标签:Singleton Javascript Pattern Object freeze instance increment counter

Source: https://javascriptpatterns.vercel.app/patterns/design-patterns/singleton-pattern

With the Singleton Pattern, we restrict the instantiation of certain classes to one single instance. This single instance is unmodifiable, and can be accessed globally throughout the application.

 

Create a Singleton in Javascritp:

Class:

let instance;

// 1. Creating the `Counter` class, which contains a `constructor`, `getInstance`, `getCount`, `increment` and `decrement` method. 
// Within the constructor, we check to make sure the class hasn't already been instantiated. 
class Counter {
  constructor() {
      if (instance) {
      throw new Error("You can only create one instance!");
    }
    this.counter = counter;
    instance = this;
  }

  getCount() {
    return this.counter;
  }

  increment() {
    return ++this.counter;
  }

  decrement() {
    return --this.counter;
  }
}

// 2. Setting a variable equal to the the frozen newly instantiated object, by using the built-in `Object.freeze` method. 
// This ensures that the newly created instance is not modifiable.
const singletonCounter = Object.freeze(new Counter());

// 3. Exporting the variable as the `default` value within the file to make it globally accessible.
export default singletonCounter;

 

2 points:

  1. If there is an instance already, we want to throw error.
  2. Use Object.freeze function to make it unmodifiable.

 

Object:

let counter = 0;

export default Object.freeze({
  getCount: () => counter,
  increment: () => ++counter,
  decrement: () => --counter,
})

 


Be carefully about using Singelton:

Depedency Hiding: When importing another module, it may not always be obvious that that module is importing a Singleton. This could lead to unexpected value modification within the Singleton, which would be reflected throughout the application.

Let's say Counter is a singelton. module A and B both import counter and call `increment` twice in each modules.

If in Moulde A, we import Module B. Then `increment` will be called 4 times. But in Module A, we only call twice, that might cause confusion when you just looking at Module A code.

Unnecessary: ES2015 Modules are singletons by default. We no longer need to explicitly create singletons to achieve this global, non-modifiable behavior.

标签:Singleton,Javascript,Pattern,Object,freeze,instance,increment,counter
From: https://www.cnblogs.com/Answer1215/p/16627783.html

相关文章

  • JavaScript基础回顾知识点记录7-事件补充说明2
    js中鼠标滚轮事件offsetWidth/offsetHeight-对象的可见宽度/高度clientWidth/clientHeight-内容的可见宽度/高度scrollWidth/scrollHeight......
  • JavaScript快速入门-06-函数
    6函数6.1函数定义  函数可以封装语句,然后在任何地方、任何时间执行。JavaScript中的函数使用function关键字声明,主要由函数名、函数参数和函数体组成。其基本语法......
  • 2022-8-25第一组孙乃宇JavaScript
    JavaScript最后元素的属性获取元素的属性所有的HTML元素,我们可以根据具体需求,自定义添加属性<divhaha="abc"id="xyz"name="123"></div>获取这个属性的值为什么na......
  • JavaScript知识-函数基础知识、匿名函数、闭包函数、箭头函数、js内置对象和方法
    目录JavaScript函数1.函数的语法格式2.无参函数3.有参函数4.关键字arguments5.函数返回值关键字return6.匿名函数(没有函数名)7.箭头函数8.函数的全局变量与局部变量9.闭包......
  • JavaScript中改变鼠标指针样式的方法
    JavaScript中改变鼠标指针样式的方法    在js中我们可以通过style对象的cursor属性来设置鼠标指针的样式,例varbody=document.querySelector("body") body.style......
  • python 3 用pyexecjs 执行 javascript 代码
    #运行js代码e=execjs.eval('a=newArray(1,2,3)')#execjs.eval()获取js环境,直接执行js代码,适用于简单的运算适用于从前端读取js代码然后运行(前后......
  • Javascript:设计模式-简单工厂模式
    工厂模式大体分为三类:简单工厂模式、工厂方法模式、抽象工厂模式。在我们日常的实现功能逻辑中,最基础的一种方法是这样的:有一个体育器材店,每一种类型的运动器材都有名称......
  • Javascript:实现继承的几种方式
    既然要实现继承,那么首先我们得有一个父类,代码如下://定义一个动物类function Animal(name){  //属性  this.name=name|| 'Animal';  //实例......
  • Javascript:设计模式-代理模式
    例:该例为书中原例,小明(xiaoming)遇到了女神(A),打算送个花来告白,刚好小明打听到女神有个朋友叫(B),自己不太好意思,所以决定让B来送花,虽然这件事儿肯定是凉了,但是作为例子还是很......
  • 「中高级前端面试」JavaScript手写代码无敌秘籍
    手写路径导航实现一个new操作符实现一个JSON.stringify实现一个JSON.parse实现一个call或apply实现一个Function.bind实现一个继承实现一个JS函数柯里化手写一个......