【编程思想】【设计模式】【结构模式Structural】享元模式flyweight
Python版
https://github.com/faif/python-patterns/blob/master/structural/flyweight.py
#!/usr/bin/env python
# -*- coding: utf-8 -*- """
*References:
http://codesnipers.com/?q=python-flyweights *TL;DR80
Minimizes memory usage by sharing data with other similar objects.
""" import weakref class FlyweightMeta(type): def __new__(mcs, name, parents, dct):
"""
Set up object pool :param name: class name
:param parents: class parents
:param dct: dict: includes class attributes, class methods,
static methods, etc
:return: new class
"""
dct['pool'] = weakref.WeakValueDictionary()
return super(FlyweightMeta, mcs).__new__(mcs, name, parents, dct) @staticmethod
def _serialize_params(cls, *args, **kwargs):
"""
Serialize input parameters to a key.
Simple implementation is just to serialize it as a string
"""
args_list = list(map(str, args))
args_list.extend([str(kwargs), cls.__name__])
key = ''.join(args_list)
return key def __call__(cls, *args, **kwargs):
key = FlyweightMeta._serialize_params(cls, *args, **kwargs)
pool = getattr(cls, 'pool', {}) instance = pool.get(key)
if instance is None:
instance = super(FlyweightMeta, cls).__call__(*args, **kwargs)
pool[key] = instance
return instance class Card(object): """The object pool. Has builtin reference counting"""
_CardPool = weakref.WeakValueDictionary() """Flyweight implementation. If the object exists in the
pool just return it (instead of creating a new one)"""
def __new__(cls, value, suit):
obj = Card._CardPool.get(value + suit)
if not obj:
obj = object.__new__(cls)
Card._CardPool[value + suit] = obj
obj.value, obj.suit = value, suit
return obj # def __init__(self, value, suit):
# self.value, self.suit = value, suit def __repr__(self):
return "<Card: %s%s>" % (self.value, self.suit) def with_metaclass(meta, *bases):
""" Provide python cross-version metaclass compatibility. """
return meta("NewBase", bases, {}) class Card2(with_metaclass(FlyweightMeta)): def __init__(self, *args, **kwargs):
# print('Init {}: {}'.format(self.__class__, (args, kwargs)))
pass if __name__ == '__main__':
# comment __new__ and uncomment __init__ to see the difference
c1 = Card('9', 'h')
c2 = Card('9', 'h')
print(c1, c2)
print(c1 == c2, c1 is c2)
print(id(c1), id(c2)) c1.temp = None
c3 = Card('9', 'h')
print(hasattr(c3, 'temp'))
c1 = c2 = c3 = None
c3 = Card('9', 'h')
print(hasattr(c3, 'temp')) # Tests with metaclass
instances_pool = getattr(Card2, 'pool')
cm1 = Card2('10', 'h', a=1)
cm2 = Card2('10', 'h', a=1)
cm3 = Card2('10', 'h', a=2) assert (cm1 == cm2) != cm3
assert (cm1 is cm2) is not cm3
assert len(instances_pool) == 2 del cm1
assert len(instances_pool) == 2 del cm2
assert len(instances_pool) == 1 del cm3
assert len(instances_pool) == 0 ### OUTPUT ###
# (<Card: 9h>, <Card: 9h>)
# (True, True)
# (31903856, 31903856)
# True
# False
Python转载版
【编程思想】【设计模式】【结构模式Structural】享元模式flyweight的更多相关文章
- 设计模式GOF23(结构型模式:代理模式,适配模式,桥接模式,组合模式,装饰模式,外观模式,享元模式)
结构型模式: – 分类: • 适配器模式.代理模式.桥接模式.装饰模式.组合模式.外观模式.享元模式 – 核心作用:是从程序的结构上实现松耦合,从而可以扩大整体的类结构,用来解决更大的问题. 结构 ...
- 设计模式(十)享元模式Flyweight(结构型)
设计模式(十)享元模式Flyweight(结构型) 说明: 相对于其它模式,Flyweight模式在PHP实现似乎没有太大的意义,因为PHP的生命周期就在一个请求,请求执行完了,php占用的资源都被释 ...
- 设计模式的征途—12.享元(Flyweight)模式
现在在大力推行节约型社会,“浪费可耻,节俭光荣”.在软件系统中,有时候也会存在资源浪费的情况,例如,在计算机内存中存储了多个完全相同或者非常相似的对象,如果这些对象的数量太多将导致系统运行代价过高.那 ...
- Java设计模式(十一) 享元模式
原创文章,同步发自作者个人博客 http://www.jasongj.com/design_pattern/flyweight/.转载请注明出处 享元模式介绍 享元模式适用场景 面向对象技术可以很好的 ...
- 七个结构模式之享元模式(Flyweight Pattern)
定义: 运用共享技术对大量细粒度对象的复用,这要求这些对象都很相似,状态变化很小.将这些对象的内部状态和外部状态进行区分,对于内部状态相同的只存储一个对象,而对不同的外部状态则采用不同的操作. 结构图 ...
- 设计模式---对象性能模式之享元模式(Flyweight)
一:概念 通过与其他类似对象共享数据来减少内存占用 如果一个应用程序使用了太多的对象, 就会造成很大的存储开销. 特别是对于大量轻量级 (细粒度)的对象,比如在文档编辑器的设计过程中,我们如果为每个字 ...
- js设计模式(8)---享元模式
0.前言 今天总结了四种设计模式,到现在有点精疲力尽了,但是还是有不少收获,很开心自己有掌握了新的东西,今天变得有了价值. 1.使用条件 1.1.网页中使用了大量资源密集型的对象: 1.2.这些对象中 ...
- 【设计模式 - 11】之享元模式(FlyWeight)
1 模式简介 当系统中存在大量对象时,非常容易造成内存溢出.为了解决这个问题,我们把这些对象中共有的部分抽象出来,如果有相同的业务请求,则直接返回在内存中已有的对象,避免重新创建,这就是享元 ...
- 设计模式21---设计模式之享元模式(Flyweight)(结构型)
1.讲解享元模式(结构型) 1.1享元模式定义 运用共享技术有效地支持大量细粒度对象. 享元:把内部状态共享出来 1.2享元模式要点 重点在于分离变与不变. 把一个对象的状态分为内部状态和外部状态,内 ...
- C#设计模式之十二享元模式(Flyweight)【结构型】
一.引言 今天我们要讲[结构型]设计模式的第六个模式,该模式是[享元模式],英文名称是:Flyweight Pattern.还是老套路,先从名字上来看看."享元"是不是可以这样 ...
随机推荐
- $router 和 $route的区别
router router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局对象,他包含了所有的路 ...
- python编写脚本,登录Github通过指定仓库指定敏感关键字搜索自动化截图生成文件【完美截图】
前言:为了避免开发人员将敏感信息写入文件传到github,所以测试人员需要检查每个仓库是否有写入,人工搜索审核比较繁琐,所以写一个脚本通过配置 配置文件,指定需要搜索的仓库和每个仓库需要搜索的关键字, ...
- Flink 实践教程:入门(6):读取 PG 数据写入 ClickHouse
作者:腾讯云流计算 Oceanus 团队 流计算 Oceanus 简介 流计算 Oceanus 是大数据产品生态体系的实时化分析利器,是基于 Apache Flink 构建的具备一站开发.无缝连接.亚 ...
- 使用 @Transactional 时常犯的N种错误
@Transactional是我们在用Spring时候几乎逃不掉的一个注解,该注解主要用来声明事务.它的实现原理是通过Spring AOP在注解修饰方法的前后织入事务管理的实现语句,所以开发者只需要通 ...
- scrapy的安装,scrapy创建项目
简要: scrapy的安装 # 1)pip install scrapy -i https://pypi.douban.com/simple(国内源) 一步到位 # 2) 报错1: building ...
- SpringCloud升级之路2020.0.x版-40. spock 单元测试封装的 WebClient(上)
本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 我们来测试下前面封装好的 WebClient,这里开始,我们使用 spock 编写 gro ...
- [hdu6582]Path
首先,从1和n跑一次dij,判断每一条边能否出现在最短路上,不能出现就删掉,然后将所有边建在图上,流量为边权,跑最小割即可. 1 #include<bits/stdc++.h> 2 usi ...
- springboot项目中常遇到的问题-初学者最容易犯的错
1.在spring中有两个main方法 2.在idea中少提代码类了,或者某类中代码依赖关系没解决掉
- [SQL]SQL Server 锁表
-- 查看被锁表: SELECT request_session_id spid, -- 锁表进程 OBJECT_NAME(resource_associated_entity_id) tableNa ...
- BZOJ 3926 诸神眷顾的幻想乡
BZOJ 3926 诸神眷顾的幻想乡 开始看错题看成了每个点度数不超过20 后来翻了翻题解原来看错题的不止我一个 既然叶子数量不超过20,考虑树上的任何一条路径,以任何点为根时,如果它不是一条从上到下 ...