【编程思想】【设计模式】【创建模式creational】Pool
Python版
https://github.com/faif/python-patterns/blob/master/creational/pool.py
#!/usr/bin/env python
# -*- coding: utf-8 -*- """
*What is this pattern about?
This pattern is used when creating an object is costly (and they are
created frequently) but only a few are used at a time. With a Pool we
can manage those instances we have as of now by caching them. Now it
is possible to skip the costly creation of an object if one is
available in the pool.
>>这个设计模式是用来创建那种花费较高但是一次只用一部分的对象,并且他们经常被创建。
>>使用Pool设计模式,我们可以通过缓存他们来管理那些我们目前拥有的实例。
>>因此,如果我们在pool中找到可用的,我们就可以节省那些花费高昂的创建实例的工作
A pool allows to 'check out' an inactive object and then to return it.
If none are available the pool creates one to provide without wait.
>>Pool允许不活动的实例'退房',然后再回来。
>>如果pool中没有可用的,他会创建一个,不需要再等待 *What does this example do?
In this example queue.Queue is used to create the pool (wrapped in a
custom ObjectPool object to use with the with statement), and it is
populated with strings.
>>在这个例子中,queue.Queue是用来创建pool的(包装在自定义ObjectPool对象中,使用with声明)
>>他使用字符串填充
As we can see, the first string object put in "yam" is USED by the
with statement. But because it is released back into the pool
afterwards it is reused by the explicit call to sample_queue.get().
>>我们可以看到,第一个放到"yam"中的字符串对象被"with"声明。
>>但是因为他被放回了poll之后,他被sample_queue.get()直接调用
Same thing happens with "sam", when the ObjectPool created insided the
function is deleted (by the GC) and the object is returned.
>>"sam"也有同样的情况,当ObjectPool创建的时候,取代了被GC删除的函数,然后对象被返回 *Where is the pattern used practically? *References:
http://stackoverflow.com/questions/1514120/python-implementation-of-the-object-pool-design-pattern
https://sourcemaking.com/design_patterns/object_pool *TL;DR80
Stores a set of initialized objects kept ready to use.
""" class ObjectPool(object): def __init__(self, queue, auto_get=False):
self._queue = queue
self.item = self._queue.get() if auto_get else None def __enter__(self):
if self.item is None:
self.item = self._queue.get()
return self.item def __exit__(self, Type, value, traceback):
if self.item is not None:
self._queue.put(self.item)
self.item = None def __del__(self):
if self.item is not None:
self._queue.put(self.item)
self.item = None def main():
try:
import queue
except ImportError: # python 2.x compatibility
import Queue as queue def test_object(queue):
pool = ObjectPool(queue, True)
print('Inside func: {}'.format(pool.item)) sample_queue = queue.Queue() sample_queue.put('yam')
with ObjectPool(sample_queue) as obj:
print('Inside with: {}'.format(obj))
print('Outside with: {}'.format(sample_queue.get())) sample_queue.put('sam')
test_object(sample_queue)
print('Outside func: {}'.format(sample_queue.get())) if not sample_queue.empty():
print(sample_queue.get()) if __name__ == '__main__':
main() ### OUTPUT ###
# Inside with: yam
# Outside with: yam
# Inside func: sam
# Outside func: sam Python转载版
Python转载版
【编程思想】【设计模式】【创建模式creational】Pool的更多相关文章
- 【编程思想】【设计模式】【创建模式creational 】工厂模式factory_method
Python版 https://github.com/faif/python-patterns/blob/master/creational/factory_method.py #!/usr/bin/ ...
- 【编程思想】【设计模式】【创建模式creational】Borg/Monostate
Python版 https://github.com/faif/python-patterns/blob/master/creational/borg.py #!/usr/bin/env python ...
- 【编程思想】【设计模式】【创建模式creational】抽象工厂模式abstract_factory
Python版 https://github.com/faif/python-patterns/blob/master/creational/abstract_factory.py #!/usr/bi ...
- 【编程思想】【设计模式】【创建模式creational】建造者模式builder
Python版 https://github.com/faif/python-patterns/blob/master/creational/builder.py #!/usr/bin/python ...
- 【编程思想】【设计模式】【创建模式creational】原形模式Prototype
Python版 https://github.com/faif/python-patterns/blob/master/creational/prototype.py #!/usr/bin/env p ...
- 【编程思想】【设计模式】【创建模式creational】lazy_evaluation
Python版 https://github.com/faif/python-patterns/blob/master/creational/lazy_evaluation.py #!/usr/bin ...
- 【java设计模式】【创建模式Creational Pattern】单例模式Singleton Pattern
//饿汉式:资源利用率较低(无论是否需要都会创建),性能较高(使用前无需判断实例是否存在,可直接使用) public class EagerSingleton{ private static fina ...
- 【java设计模式】【创建模式Creational Pattern】抽象工厂模式Abstract Factory Pattern
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAW0AAABvCAIAAACo3AbKAAALvUlEQVR4nO1dUa7cOA7U/c+zwJxkf4
- 【java设计模式】【创建模式Creational Pattern】建造模式Builder Pattern
package com.tn.pattern; public class Client { public static void main(String[] args) { Director dire ...
随机推荐
- springboot使用之请求参数与基本注解
@PathVariable 作用:@PathVariable是spring3.0的一个新功能:接收请求路径中占位符的值,将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariabl ...
- webpack 打包html文件
webpack 打包html文件 webpack.config.js配置文件内容为: /** * loader: 1. 下载 2. 使用(配置) * plugins:1. 下载 2. 引入 3.使用 ...
- redux 的简单实用案例
redux 的简单实用案例 整体思想与结构 创建一个Action 创建一个Reducer 创建Store 在App组件开始使用 整体思想与结构 文件目录如下: 构建 action,通过创建一个函数,然 ...
- 表现层(jsp)、持久层(dao)、业务层(逻辑层、service)
转自:http://www.blogjava.net/jiabao/archive/2007/04/08/109189.html 为了实现web层(struts)和持久层(Hibernate)之间的松 ...
- cmd 命令 导出导入oracle数据库 的 表
原地址:https://www.cnblogs.com/mysterious-killer/p/11671741.html (防止) 导出: 不要数据的:exp username/pwd@localh ...
- [spojQTREE7]Query on a tree VII
即QTREE5和QTREE6组合,即将原本维护子树范围内点数改为维护子树范围内最小值即可,由于最小值没有可减性,因此需要使用set (虽然形式上与QTREE5类似,但QTREE5维护的信息更巧妙一些, ...
- [bzoj1741]穿越小行星群
将每一行/每一列作为一个点,对于一个障碍(x,y),要么第x行和第y列的状态(是否攻击)只需要有一个就可以了,将第x行和第y列连边,就是二分图的最小点覆盖=最大匹配数. 1 #include<b ...
- [hdu5379]Mahjong tree
一棵子树的每一个儿子相当于划分一个区间,同时这些区间一定要存在一个点连续(直接的儿子),因此每一棵树最多只有两个儿子存在子树,并且这两个儿子所分到的区间一定是该区间最左和最右两段,所以ans*=(so ...
- [noi1755]Trie
定义S对应的数组为$a_{i}=\min_{0\le j<i,S_{j}=S_{i}}i-j$,特别的,若不存在j,令$a_{i}=i$,那么容易发现存在双射关系就意味这两者对应的数组相同 因此 ...
- 新玩法-使用AllArgsConstructor+filal代替autowired
和下面的代码一样: Springboot官方建议使用final来修饰成员变量,然后通过构造方法来进行注入原因:final修饰的成员变量是不能够被修改的,反射那就没办法了 还有一种写法: @Requir ...