【编程思想】【设计模式】【创建模式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 ...
随机推荐
- Python 官方研讨会:彻底移除 GIL 真的可行么?
作者:Łukasz Langa 译者:豌豆花下猫,来源:Python猫 原文:https://lukasz.langa.pl/5d044f91-49c1-4170-aed1-62b6763e6ad0 ...
- Python基础(递归函数)
def age(n): if n == 1: return 18 else: return age(n - 1) + 2 ret=age(100) print(ret)#216 def test(nu ...
- [luogu4607]反回文串
参考ARC064F 令$h(n)=\begin{cases}n(n为奇数)\\\frac{n}{2}(n为偶数)\end{cases}$,$f(n)$定义与ARC064F相同,答案即$\sum_{d| ...
- [atARC084D]Small Multiple
构造一张图:$\forall x$,向$10x$连一条边权为0的边,向$x+1$连1条边权为1的边,那么0到$i$的代价即为$i$各位数字之和 考虑到我们只关心于当前点的两个特征:1.模$n$的余数( ...
- 【Microsoft Azure 的1024种玩法】七.Azure云端搭建部署属于自己的维基百科
[简介] MediaWiki是全球最著名的开源wiki程序,运行于PHP+MySQL环境.MediaWiki从2002年2月25日被作为维基百科全书的系统软件,并有大量其他应用实例.MediaWiki ...
- Codeforces 1326F2 - Wise Men (Hard Version)(FWT+整数划分)
Codeforces 题目传送门 & 洛谷题目传送门 qwq 这题大约是二十来天前 AC 的罢,为何拖到此时才完成这篇题解,由此可见我是个名副其实的大鸽子( 这是我上 M 的那场我没切掉的 F ...
- Codeforces 559E - Gerald and Path(dp)
题面传送门 真·难度 *3000 的 D1E hb 跟我们说"做不出来不太应该". 首先我们将所有线段按 \(a_i\) 从小到大排序,一个很显然的想法是 \(dp_{i,j,d} ...
- python-django-ORM模型
ORM模型: Object Relational Mapping 对象关系映射 配置引擎的时候最好直接复制: DATABASES = { 'default': { 'ENGINE': 'django. ...
- requests+bs4爬取豌豆荚排行榜及下载排行榜app
爬取排行榜应用信息 爬取豌豆荚排行榜app信息 - app_detail_url - 应用详情页url - app_image_url - 应用图片url - app_name - 应用名称 - ap ...
- CentOS安装配置Hadoop 1.2.1(伪分布模式)
CentOS安装配置Hadoop1.2.1 1.下载安装文件 下载2个安装文件 JAVA环境:jdk-6u21-linux-i586.bin Hadoop环境:hadoop-1.2.1.tar.gz ...