为什么Borg模式比Singleton模式更好?
我问,因为我没有看到它们导致任何不同.
博格:
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()
Run Code Online (Sandbox Code Playgroud)
辛格尔顿:
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()
Run Code Online (Sandbox Code Playgroud)
我想在这里显示的是服务对象,无论是作为Borg还是Singleton实现,都有一个非常重要的内部状态(它提供了一些基于它的服务)(我的意思是它必须是有用的东西,它不是Singleton/Borg只是为了有趣).
而且这个州必须被引入.这里的Singleton实现更直接,因为我们将init视为全局状态的设置.我发现Borg对象必须查询其内部状态以查看它是否应该自行更新.
你拥有的内部状态越多,情况就越糟糕.例如,如果对象必须侦听应用程序的拆除信号以将其寄存器保存到磁盘,那么该注册也应该只执行一次,使用Singleton会更容易.
在数据库中模拟Tagged union的最佳方法是什么?我在谈论这样的事情:
create table t1 {
vehicle_id INTEGER NOT NULL REFERENCES car(id) OR motor(id) -- not valid
...
}
Run Code Online (Sandbox Code Playgroud)
其中vehicle_id将在汽车表或电机表中为id,并且它将知道哪个.
(假设电动机和汽车桌没有任何共同点