为什么 Borg 模式比 Python 中的单例模式更好 [英] Why is the Borg pattern better than the Singleton pattern in Python

查看:53
本文介绍了为什么 Borg 模式比 Python 中的单例模式更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 Borg 模式单例模式?

我问是因为我没有看到它们会导致任何不同.

I ask because I don't see them resulting in anything different.

博格:

class Borg:
  __shared_state = {}
  # init internal state variables here
  __register = {}
  def __init__(self):
    self.__dict__ = self.__shared_state
    if not self.__register:
      self._init_default_register()

单身:

class Singleton:
  def __init__(self):
    # init internal state variables here
    self.__register = {}
    self._init_default_register()

# singleton mechanics external to class, for example this in the module
Singleton = Singleton()

我想在这里展示的是服务对象,无论是实现为 Borg 还是 Singleton,都有一个重要的内部状态(它基于它提供一些服务)(我的意思是它必须是有用的东西,它不是一个 Singleton/博格只是为了好玩).

What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).

而且这个状态必须被初始化.这里的 Singleton 实现更直接,因为我们将 init 视为全局状态的设置.我觉得 Borg 对象必须查询其内部状态以查看它是否应该自我更新,这很尴尬.

And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat init as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.

您拥有的内部状态越多,情况就越糟.例如,如果对象必须侦听应用程序的拆卸信号以将其注册保存到磁盘,则该注册也应该只进行一次,这对于单例更容易.

It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.

推荐答案

borg 不同的真正原因归结为子类化.

The real reason that borg is different comes down to subclassing.

如果你对一个 borg 进行子类化,子类的对象与它们的父类对象具有相同的状态,除非你显式地覆盖该子类中的共享状态.单例模式的每个子类都有自己的状态,因此会产生不同的对象.

If you subclass a borg, the subclass' objects have the same state as their parents classes objects, unless you explicitly override the shared state in that subclass. Each subclass of the singleton pattern has its own state and therefore will produce different objects.

同样在单例模式中,对象实际上是相同的,而不仅仅是状态(即使状态是唯一真正重要的东西).

Also in the singleton pattern the objects are actually the same, not just the state (even though the state is the only thing that really matters).

这篇关于为什么 Borg 模式比 Python 中的单例模式更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆