亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么Borg模式比Python中的Singleton模式更好

為什么Borg模式比Python中的Singleton模式更好

一只斗牛犬 2019-12-12 14:26:18
為什么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()單身人士: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 moduleSingleton = Singleton()我想在這里顯示的是,服務對象,無論是實現為Borg還是Singleton,都具有不平凡的內部狀態(它基于該狀態提供一些服務)(我的意思是它必須是有用的東西,而不僅僅是Singleton / Borg好玩)。而這種狀態必須被初始化。這里的Singleton實現更為簡單,因為我們將init視為全局狀態的設置。我發現Borg對象必須查詢其內部狀態以查看是否應該更新自身很尷尬。內部狀態越多,情況就越糟。例如,如果對象必須偵聽應用程序的拆除信號以將其寄存器保存到磁盤,則該注冊也應僅執行一次,并且使用Singleton會更容易。
查看完整描述

3 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

博格與眾不同的真正原因歸結為子類化。

如果將borg子類化,則子類的對象與其父類對象具有相同的狀態,除非您顯式覆蓋該子類中的共享狀態。單例模式的每個子類都有其自己的狀態,因此將產生不同的對象。

同樣在單例模式中,對象實際上是相同的,而不僅僅是狀態(即使狀態是唯一真正重要的東西)。


查看完整回答
反對 回復 2019-12-12
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

在python中,如果想要一個可以從任何地方訪問的唯一“對象”,只需創建一個Unique僅包含靜態屬性@staticmethods和@classmethods的類;您可以將其稱為唯一模式。在這里,我實現并比較3種模式:


獨特


#Unique Pattern

class Unique:

#Define some static variables here

    x = 1

    @classmethod

    def init(cls):

        #Define any computation performed when assigning to a "new" object

        return cls

辛格爾頓


#Singleton Pattern

class Singleton:


    __single = None 


    def __init__(self):

        if not Singleton.__single:

            #Your definitions here

            self.x = 1 

        else:

            raise RuntimeError('A Singleton already exists') 


    @classmethod

    def getInstance(cls):

        if not cls.__single:

            cls.__single = Singleton()

        return cls.__single

博格


#Borg Pattern

class Borg:


    __monostate = None


    def __init__(self):

        if not Borg.__monostate:

            Borg.__monostate = self.__dict__

            #Your definitions here

            self.x = 1


        else:

            self.__dict__ = Borg.__monostate

測試


#SINGLETON

print "\nSINGLETON\n"

A = Singleton.getInstance()

B = Singleton.getInstance()


print "At first B.x = {} and A.x = {}".format(B.x,A.x)

A.x = 2

print "After A.x = 2"

print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)

print  "Are A and B the same object? Answer: {}".format(id(A)==id(B))



#BORG

print "\nBORG\n"

A = Borg()

B = Borg()


print "At first B.x = {} and A.x = {}".format(B.x,A.x)

A.x = 2

print "After A.x = 2"

print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)

print  "Are A and B the same object? Answer: {}".format(id(A)==id(B))



#UNIQUE

print "\nUNIQUE\n"

A = Unique.init()

B = Unique.init()


print "At first B.x = {} and A.x = {}".format(B.x,A.x)

A.x = 2

print "After A.x = 2"

print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x)

print  "Are A and B the same object? Answer: {}".format(id(A)==id(B))

輸出:


辛格爾頓


At first B.x = 1 and A.x = 1

After A.x = 2

Now both B.x = 2 and A.x = 2


Are A and B the same object? Answer: True


BORG


At first B.x = 1 and A.x = 1

After A.x = 2

Now both B.x = 2 and A.x = 2


Are A and B the same object? Answer: False


UNIQUE


At first B.x = 1 and A.x = 1

After A.x = 2

Now both B.x = 2 and A.x = 2


Are A and B the same object? Answer: True

在我看來,唯一實現是最簡單的,其次是Borg,最后是Singleton,其定義所需的兩個函數數量很少。


查看完整回答
反對 回復 2019-12-12
?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

它不是。通常不建議在python中使用以下模式:


class Singleton(object):


 _instance = None


 def __init__(self, ...):

  ...


 @classmethod

 def instance(cls):

  if cls._instance is None:

   cls._instance = cls(...)

  return cls._instance

使用類方法獲取實例而不是構造函數的地方。Python的元編程允許更好的方法,例如Wikipedia上的方法:


class Singleton(type):

    def __init__(cls, name, bases, dict):

        super(Singleton, cls).__init__(name, bases, dict)

        cls.instance = None


    def __call__(cls, *args, **kw):

        if cls.instance is None:

            cls.instance = super(Singleton, cls).__call__(*args, **kw)


        return cls.instance


class MyClass(object):

    __metaclass__ = Singleton


print MyClass()

print MyClass()


查看完整回答
反對 回復 2019-12-12
  • 3 回答
  • 0 關注
  • 486 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號