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的更多相关文章

  1. 【编程思想】【设计模式】【创建模式creational 】工厂模式factory_method

    Python版 https://github.com/faif/python-patterns/blob/master/creational/factory_method.py #!/usr/bin/ ...

  2. 【编程思想】【设计模式】【创建模式creational】Borg/Monostate

    Python版 https://github.com/faif/python-patterns/blob/master/creational/borg.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. 4.ASCII码排序

    描述 输入三个字符(可以重复)后,按各字符的ASCII码从小到大的顺序输出这三个字符. 输入 第一行输入一个数N,表示有N组测试数据.后面的N行输入多组数据,每组输入数据都是占一行,有三个字符组成,之 ...

  2. 加班时的灵感迸发,我用selenium做了个窗口化的爬*宝数据。(附源码链接)

    完整代码&火狐浏览器驱动下载链接:https://pan.baidu.com/s/1pc8HnHNY8BvZLvNOdHwHBw 提取码:4c08 双十一刚过,想着某宝的信息看起来有些少很难做 ...

  3. typing使用

    官方文档: typing 注: typing是python3.5(PEP484)开始的 可用于: 类型检查器.集成开发环境.静态检查器等, 但是不强制使用 使用方式 两种使用方式 别名: 先定义=, ...

  4. 力扣 - 剑指 Offer 22. 链表中倒数第k个节点

    题目 剑指 Offer 22. 链表中倒数第k个节点 思路1(栈) 既然要倒数第k个节点,那我们直接把所有节点放到栈(先进后出)里面,然后pop弹出k个元素就可以了 代码 class Solution ...

  5. x86汇编反编译到c语言之——(2)if语句

    一. 测试的C语句及编译后的x86汇编代码 int a; int b; int main(void) { int c; if (c) a = 4; else b = 5; return 0; } 1 ...

  6. Linux设置默认的声卡

    首先查看自己电脑上的声卡 使用命令行查看 orangepi@orangepi3:~$ ll /proc/asound/ total 0 dr-xr-xr-x 4 root root 0 Dec 23 ...

  7. 快速沃尔什变换&快速莫比乌斯变换小记

    u1s1 距离省选只剩 5 days 了,现在学新算法真的合适吗(( 位运算卷积 众所周知,对于最普通的卷积 \(c_i=\sum\limits_{j+k=i}a_jb_k\),\(a_jb_k\) ...

  8. BZOJ 3453 - tyvj 1858 XLkxc(插值+推式子)

    题面传送门 首先根据我们刚学插值时学的理论知识,\(f(i)\) 是关于 \(i\) 的 \(k+1\) 次多项式.而 \(g(x)\) 是 \(f(x)\) 的前缀和,根据有限微积分那一套理论,\( ...

  9. Matlab流体后处理中的奇淫巧术总结

    Matlab流体后处理中的奇淫巧术总结 主要参考\demos\volvec.m示例 1.等值面绘制 %% Isosurface of MRI Data cla load mri D = squeeze ...

  10. NCBI SRA数据如何进行md5校验?

    下了一些sra数据库中的公共数据,因为pretech和aspera不稳定,稍微大点的文件经常传断,部分文件我只能通过本地下载再上传. 那么问题来了,sra没有md5校验,我怎么知道我数据的完整性,尤其 ...