亲宝软件园·资讯

展开

聊聊python里怎样用Borg pattern实现的单例模式

人气:0

有如下 borg pattern 的实现:

class Borg(object):
  __shared_state = {}

  def __init__(self):
    self.__dict__ = self.__shared_state
    self.state = 'Init'

  def __str__(self):
    return self.state

之前一直看不懂为什么 Borg class 要那样实现, 后来学到两个知识点后发现原来这么简单明了:

试着跑一下:

if __name__ == '__main__':
  rm1 = Borg()
  rm2 = Borg()

  rm1.state = 'Idle'
  rm2.state = 'Running'

  print('rm1: {0}'.format(rm1))
  print('rm2: {0}'.format(rm2))

  rm2.state = 'Zombie'

  print('rm1: {0}'.format(rm1))
  print('rm2: {0}'.format(rm2))

  print('rm1 id: {0}'.format(id(rm1)))
  print('rm2 id: {0}'.format(id(rm2)))

  rm3 = YourBorg()

  print('rm1: {0}'.format(rm1))
  print('rm2: {0}'.format(rm2))
  print('rm3: {0}'.format(rm3))

其结果为:

### OUTPUT ###
# rm1: Running
# rm2: Running
# rm1: Zombie
# rm2: Zombie
# rm1 id: 140732837899224
# rm2 id: 140732837899296
# rm1: Init
# rm2: Init
# rm3: Init

本文代码来自: https://github.com/faif/python-patterns/blob/master/patterns/creational/borg.py

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论