python设计模式(享元模式)
来源:互联网 发布:linux主目录是什么 编辑:程序博客网 时间:2024/06/02 00:30
学习版本3.5.2
享元模式的概念:在一个系统中如果有多个相同的对象,那么只共享一份,不必每一个都去实例化一个对象。像python中的数字变量就是用的享元模式。
写一个例子,用享元对象去存字符串,在享元对象的工厂中包涵了享元对象池。
class Flyweight(object): def __init__(self, str): self.str = str def display(self): print("show the string: " + self.str)class FlyweightFactory(object): def __init__(self): self.flyweights = {} def getFlyweight(self, obj): flyweight = self.flyweights.get(obj) if flyweight == None: flyweight = Flyweight(str(obj)) self.flyweights[obj] = flyweight return flyweight def showFlyweights(self): for i in self.flyweights: self.flyweights[i].display() print(len(self.flyweights))if __name__ == "__main__": flyweightfactory = FlyweightFactory() fly1 = flyweightfactory.getFlyweight("hello1") fly2 = flyweightfactory.getFlyweight("hello1") fly3 = flyweightfactory.getFlyweight("hello2") fly4 = flyweightfactory.getFlyweight("hello2") fly5 = flyweightfactory.getFlyweight("hello3") flyweightfactory.showFlyweights()
运行结果
show the string: hello2show the string: hello1show the string: hello33
阅读全文
0 0
- python设计模式之享元模式
- Python设计模式(十八)【享元模式】
- python设计模式之享元模式
- Python设计模式-享元模式
- 设计模式-享元模式-flyweight-python??
- python设计模式之享元模式
- python设计模式(享元模式)
- 设计模式---享元模式
- 设计模式 享元模式
- 设计模式 - 享元模式
- 设计模式:享元模式
- 设计模式 - 享元模式
- 设计模式-享元模式
- 设计模式---------享元模式
- 设计模式:享元模式
- 设计模式--享元模式
- 设计模式-享元模式
- 设计模式:享元模式
- Intellij IDEA中serialVersionUID配置
- [杂题] HDU5288: OO’s Sequence
- C++多态的笼统解释
- Shadowsocks安装及配置
- dataguard异机安装从库时遇到的几个问题及解决方法
- python设计模式(享元模式)
- L
- iBatis中RowHandler处理大数据量的导出
- tf.name_scope and tf.variable_scope
- 关于Android通过webview与js交互的方法
- Spark性能优化:资源调优篇
- 文化价值观思考
- Java homework5
- MySQL分区和分表