Python版

https://github.com/faif/python-patterns/blob/master/creational/borg.py

#!/usr/bin/env python
# -*- coding: utf-8 -*- """
*What is this pattern about?
The Borg pattern (also known as the Monostate pattern) is a way to
implement singleton behavior, but instead of having only one instance
of a class, there are multiple instances that share the same state. In
other words, the focus is on sharing state instead of sharing instance
identity.
>>Borg设计模式(我们通常叫它Monostate模式)是一个用来实现单例的行为,
>>但是它不是一个类只有一个实例,它有很多实例共享相同的状态。
>>换句话说,它专注在共享状态而不是共享实例 *What does this example do?
To understand the implementation of this pattern in Python, it is
important to know that, in Python, instance attributes are stored in a
attribute dictionary called __dict__.
>>为了弄明白这个设计模式在python中的实现,我们必须要知道,
>>在python中,实例的属性是存储在一个属性字典中,叫做__dict__
Usually, each instance will have
its own dictionary, but the Borg pattern modifies this so that all
instances have the same dictionary.
>>通常来说,每个实例都有它自己的字典,但是Borg模式修改了他
>>所以所有实例都有相同的字典
In this example, the __shared_state attribute will be the dictionary
shared between all instances, and this is ensured by assigining
__shared_state to the __dict__ variable when initializing a new
instance (i.e., in the __init__ method).
>>在这个例子中,属性__shared_state作为字典被所有实例共享,
>>这就确保了在初始化一个实例的时候(例如 __init__方法),
Other attributes are usually
added to the instance's attribute dictionary, but, since the attribute
dictionary itself is shared (which is __shared_state), all other
attributes will also be shared.
>>其他的属性其他属性经常被添加到实例属性字典,但是,因为属性字典本身是被共享的
>>(__shared_state),所以所有其他的属性也是被共享的
For this reason, when the attribute self.state is modified using
instance rm2, the value of self.state in instance rm1 also chages. The
same happends if self.state is modified using rm3, which is an
instance from a subclass.
>>因为这个原因,但是属性self.state被实例rm2修改之后,rm1中self.state的值也改变了
>>如果子类的实例rm3修改了self.state也会发生相同的事情
Notice that even though they share attributes, the instances are not
the same, as seen by their ids.
>>注意,即使他们共享属性,实例也是不一样的,从他们的id就能看出来 *Where is the pattern used practically?
Sharing state is useful in applications like managing database connections:
>>共享属性在管理数据库连接的应用中非常实用
https://github.com/onetwopunch/pythonDbTemplate/blob/master/database.py *References:
https://fkromer.github.io/python-pattern-references/design/#singleton *TL;DR80
Provides singletone-like behavior sharing state between instances.
""" class Borg(object):
__shared_state = {} def __init__(self):
self.__dict__ = self.__shared_state
self.state = 'Init' def __str__(self):
return self.state class YourBorg(Borg):
pass 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

Python转载版

【编程思想】【设计模式】【创建模式creational】Borg/Monostate的更多相关文章

  1. 【编程思想】【设计模式】【创建模式creational 】工厂模式factory_method

    Python版 https://github.com/faif/python-patterns/blob/master/creational/factory_method.py #!/usr/bin/ ...

  2. 【编程思想】【设计模式】【创建模式creational】Pool

    Python版 https://github.com/faif/python-patterns/blob/master/creational/pool.py #!/usr/bin/env python ...

  3. 【编程思想】【设计模式】【创建模式creational】抽象工厂模式abstract_factory

    Python版 https://github.com/faif/python-patterns/blob/master/creational/abstract_factory.py #!/usr/bi ...

  4. 【编程思想】【设计模式】【创建模式creational】建造者模式builder

    Python版 https://github.com/faif/python-patterns/blob/master/creational/builder.py #!/usr/bin/python ...

  5. 【编程思想】【设计模式】【创建模式creational】原形模式Prototype

    Python版 https://github.com/faif/python-patterns/blob/master/creational/prototype.py #!/usr/bin/env p ...

  6. 【编程思想】【设计模式】【创建模式creational】lazy_evaluation

    Python版 https://github.com/faif/python-patterns/blob/master/creational/lazy_evaluation.py #!/usr/bin ...

  7. 【java设计模式】【创建模式Creational Pattern】单例模式Singleton Pattern

    //饿汉式:资源利用率较低(无论是否需要都会创建),性能较高(使用前无需判断实例是否存在,可直接使用) public class EagerSingleton{ private static fina ...

  8. 【java设计模式】【创建模式Creational Pattern】抽象工厂模式Abstract Factory Pattern

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW0AAABvCAIAAACo3AbKAAALvUlEQVR4nO1dUa7cOA7U/c+zwJxkf4

  9. 【java设计模式】【创建模式Creational Pattern】建造模式Builder Pattern

    package com.tn.pattern; public class Client { public static void main(String[] args) { Director dire ...

随机推荐

  1. Linux下安装、配置、启动与访问RabbitMQ

    一.下载 首先第一步要下载三个rpm安装包,为了方便安装与学习,给出下载途径 网盘网址:https://pan.baidu.com/s/18Z64Lb9KQpRh10RzqZBdoQ 提取码:094v ...

  2. 热门剧本杀与 SaaS 的不解之缘

    近年来,"剧本杀"这种以剧本为核心,玩家分别扮演不同角色推理案情找出真凶的娱乐项目在年轻人的范围内迅速传开,已悄然形成了一个市场规模超百亿的新兴产业,吸引了大量淘金者.而在互联网时 ...

  3. PTA 哈利·波特的考试 (25分)

    PTA 哈利·波特的考试 (25分) 哈利·波特要考试了,他需要你的帮助.这门课学的是用魔咒将一种动物变成另一种动物的本事.例如将猫变成老鼠的魔咒是haha,将老鼠变成鱼的魔咒是hehe等等.反方向变 ...

  4. hudi clustering 数据聚集(一)

    概要 数据湖的业务场景主要包括对数据库.日志.文件的分析,而管理数据湖有两点比较重要:写入的吞吐量和查询性能,这里主要说明以下问题: 1.为了获得更好的写入吞吐量,通常把数据直接写入文件中,这种情况下 ...

  5. 【JAVA】编程(4)---摇色子

    作业要求: 利用" Math.random ( )  "生成随机数的方法来模拟同时摇三个色子获得的点数:点数的多少不同,也会导致不同的输出结果:可适当对程序增添一些更有趣的功能: ...

  6. [Vue]浅谈Vue3组合式API带来的好处以及选项API的坏处

    前言 如果是经验不够多的同志在学习Vue的时候,在最开始会接触到Vue传统的方式(选项式API),后边会接触到Vue3的新方式 -- 组合式API.相信会有不少同志会陷入迷茫,因为我第一次听到新的名词 ...

  7. 【JavaScript使用技巧】三个截取字符串中的子串,你用的哪个

    [JavaScript使用技巧]三个截取字符串中的子串,你用的哪个 博客说明 文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢! slice( ...

  8. Swift-技巧(八)CVPixelBuffer To CGImage

    摘要 Swift 中图像的表现形式不只是 Image,还有更加底层的方式,比如 CVPixelBuffer 像素缓存形式,那么像素缓存转换为可以在应用中展示的 CGImage,就要知道有哪些处理了. ...

  9. Insights直播回顾,对话专家,HMS Core 6创新能力解读

    HMS Core Insights第八期直播–对话专家,HMS Core 6创新能力解读,已于11月25日圆满结束,本期直播与小伙伴们一同了解了HMS Core 6在图形.媒体以及连接与通信领域推出的 ...

  10. Yarp 让系统内调度更灵活

    简介 Yarp 是微软团队开发的一个反向代理组件, 除了常规的 http 和 https 转换通讯,它最大的特点是可定制化,很容易根据特定场景开发出需要的定制代理通道. 详细介绍:https://de ...