c#中singleton_在JavaScript中使用Singleton

c#中singleton

The Singleton is one of the most well known and hated design patterns amongst developers. It is very easy to implement a basic version of the singleton pattern (probably why it’s abused so much). In this article, we’ll take a look at what singletons are and how to best implement them in JavaScript.

Singleton是开发人员中最著名和最讨厌的设计模式之一。 实现单例模式的基本版本非常容易(可能是为什么滥用如此之多)。 在本文中,我们将研究什么是单例以及如何最好地在JavaScript中实现它们。

There are times when you need to have only one instance of a class and no more. It could be some kind of resource manager, one that maintains I/O ports of your application or some global lookup for values. That’s where singletons come in.

有时候,您只需要一个类的一个实例,而不再需要。 它可以是某种资源管理器,可以维护应用程序的I / O端口,也可以进行全局值查找。 那就是单身人士进来的地方。

Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one. In other words, Singletons are created exactly once during the runtime of the application in the global scope.

单例用于创建类的实例(如果该实例不存在),否则返回现有实例的引用。 换句话说,在全局范围内的应用程序运行期间,仅创建一次Singleton。

You might ask, why use singletons in a language with global variables? They don’t seem very different from global variables (or static ones), and most regard them as “glorified globals”. JavaScript in particular has that difference very very blurred, because the following code…

您可能会问,为什么在具有全局变量的语言中使用单例? 它们似乎与全局变量(或静态变量)没有太大不同,大多数人将它们视为“标准化的全局变量”。 尤其是JavaScript,其差异非常非常模糊,因为以下代码…

var Alliagator = {
  color: "green", 
  getColor: function() { 
    console.log(color);
  };
}

Is technically a singleton object, since it’s an object literal - which means that the object with that name is unique throughout the application (since it can’t be redeclared).

从技术上讲,它是一个单例对象,因为它是对象文字,这意味着具有该名称的对象在整个应用程序中都是唯一的(因为无法重新声明)。

This seems to have a lot in common with global variables in JavaScript as well. So what’s the difference?

这似乎与JavaScript中的全局变量也有很多共同点。 那有什么区别呢?

  • For starters, global variables are lexically scoped whereas singletons are not, meaning if there is another variable with the same name as the global variable inside a programming block, then that reference is given priority; In case of singletons, being sort of static in declaration, should not have that reference redeclared.

    对于初学者来说,全局变量在词法上是作用域的,而单例不是,这意味着如果在编程块中还有另一个与全局变量同名的变量,则该引用具有优先权; 在单例的情况下,声明中是静态的,不应重新声明该引用。
  • The value of a singleton is modified through methods.

    单例的值通过方法修改。
  • The singleton is not freed until the termination of the program, which is likely not the case for a global variable.

    直到程序终止,才释放单例,这对于全局变量可能不是这种情况。

An interesting advantage of a singleton is that it’s thread-safe. While that feature is not really applicable to Javascript, this comes in handy in languages like C++. This is just a case to prove the point that it’s not really weird to go for singletons even in a language that supports global variables.

单例的一个有趣的优点是它是线程安全的。 尽管该功能并非真正适用于Javascript,但在C ++等语言中非常有用。 这只是一个例子,可以证明即使使用支持全局变量的语言,单身人士也不是很奇怪。

There are scenarios where singletons are handy. Some applications of singletons are logger objects or configuration settings classes.

在某些情况下,单例很方便。 单例的某些应用是记录器对象或配置设置类。

A quick way to declare a singleton would be:

声明单例的快速方法是:

// Declare them like this
var SingletonInstance = { 
 method1: function () { ... }
 method2: function () { ... } 
};

// and use them as such
console.log(SingletonInstance.method1());
console.log(SingletonInstance.method2());

While this may be the easy way, it’s not necessarily the best. Another way would be to use factory classes that allows us to create a singleton once.

尽管这可能是简单的方法,但不一定是最好的方法。 另一种方法是使用允许我们一次创建一个单例的工厂类。

var SingletonFactory = (function(){
  function SingletonClass() {
    // ...
  }
  var instance;
  return {
    getInstance: function(){
      // check if instance is available
      if (!instance) {
        instance = new SingletonClass();
        delete instance.constructor; // or set it to null
      }
      return instance;
    }
  };
})();

This is better than the last example because the class definition is private and the constructor is deleted after the first instance creation, which helps us prevent duplicate singletons in the program. But the above approach looks a lot like the factory pattern.

这比上一个示例更好,因为类定义是私有的,并且在创建第一个实例后删除了构造函数,这有助于我们防止程序中出现重复的单例。 但是以上方法看起来很像工厂模式。

Perhaps the cleanest approach is to use a combination of ES6 classes, const and Object.freeze():

也许最干净的方法是结合使用ES6 constObject.freeze()

class Singleton {
  constructor(){
   ...
  }

  method1(){
    ...
  }

  method2(){
    ...
  }
}

const singletonInstance = new Singleton();
Object.freeze(singletonInstance);

We can go a little further and write this singleton in a module and then export it with the ES6 export functionality.

我们可以更进一步,将此单例写入模块,然后使用ES6导出功能将其导出

export default singletonInstance;

Then use that singleton by importing it:

然后通过导入使用该单例:

import mySingleton from './path-to-my-singleton-definition.js'; 
mySingleton.method_1() // Now use your singletons

So take your pick, find which approach works best for your application and puts readability first.

因此,请选择哪种方法,哪种方法最适合您的应用程序,并将可读性放在首位。

结论 (Conclusion)

It’s quite likely that you will run into overwhelming online literature on how singletons are bad for object oriented designs. The idea is to use singletons where it doesn’t affect the state of the application, because if you fail to follow, then testing goes right out the window. This severely limits their usage in big applications. Most developers agree that global state is bad, but they love them too much to look at its bad sides while others go extreme lengths to avoid using global states. Whether singletons are good or bad, understanding this fundamental design pattern and adding it to your programming toolkit is always a wise idea.

您很可能会遇到无数在线文献,这些文献涉及单例对面向对象设计的不利影响。 想法是在不影响应用程序状态的情况下使用单例,因为如果您不遵循,那么测试就直接在窗口之外。 这严重限制了它们在大型应用程序中的使用。 大多数开发人员都认为全局状态是不好的,但他们太喜欢它们了,以至于看不到它的不利方面,而其他开发人员则竭尽全力避免使用全局状态。 无论单例是好是坏,理解这种基本设计模式并将其添加到编程工具包中始终是一个明智的主意。

进一步阅读 (Further Reading)

Check out this blog post by Misko Hevery for more insight into the global state issue with singletons.

查看Misko Hevery的博客文章,以更深入地了解单身人士的全球性问题。

翻译自: https://www.digitalocean.com/community/tutorials/js-js-singletons

c#中singleton

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值