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. Mysql教程:(五)多表查询

    多表查询 select name,student.class,student.number,maths,chinese,english from student,score where student ...

  2. JavaScript高阶函数之filter、map、reduce

    JavaScript高阶函数 filter(过滤) 用法: 用于过滤,就是把数组中的每个元素,使用回调函数func进行校验,回调函数func返回一个布尔值,将返回值为 true 的元素放入新数组 参数 ...

  3. springboot使用之请求参数与基本注解

    @PathVariable 作用:@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值,将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariabl ...

  4. webpack--初试webpack( 核心、体验、资源打包)

    前言 webpack是当前前端项目中最常用的资源构建工具,从本文开始,来总结记录一下关于webpack的学习. 正文 1.webpack简介 webpack官网(https://webpack.doc ...

  5. [loj3528]位移寄存器

    当$s=0$时(求最小值): 若$x_{0},x_{1},...,x_{n-1}$和$y_{0},y_{1},...,y_{n-1}$像题中所给的方式存储在$r[0][0..nk-1]$和$r[1][ ...

  6. [cf1236F]Alice and the Cactus

    首先,我们要用到期望的一个性质: 对于两个随机变量$X$和$Y$(不需要相互独立),有$E(X+Y)=E(X)+E(Y)$ 另外,对于一个仙人掌,令$n$为点数,$m$为边数,$c$为简单环个数,$X ...

  7. [luogu2303]Longge的问题

    1 #include<bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 ll n,ans; 5 ll phi(l ...

  8. 简单的MISC,writerup

    (Tips:此题是我自己出给新生写的题目) 解压压缩包,发现两个文件,一个压缩包一个图片 尝试解压,发现有密码,正常思路及密码被藏在了图片里 把图片拉进010editor,无发现,再拉进stegsol ...

  9. 前端---梳理 http 知识体系 2

    为什么要有HTTPS HTTP 天生具有明文的特点,整个传输过程完全透明,任何人都能够在链路中截获.修改或者伪造请求 / 响应报文,数据不具有安全性.仅凭HTTP 自身是无法解决的,需要引入新的HTT ...

  10. 一个没被spring管理的类怎么创建对象并使用里面的方法

    一个对象new出来的,如果不是构造器注入@Data 也不好使啊,尝试构造器注入一下,或者set进去 第二次尝试使用这个. 向这种只能构造器注入或者通过上面的set方法来注入了,component是不好 ...