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. 在 macOS 上运行无限许可的 Nessus 10

    请访问原文链接:https://sysin.org/blog/nessus-unlimited-on-macos/,查看最新版.原创作品,转载请保留出处. 作者:gc(at)sysin.org,主页: ...

  2. 数组 & 对象 & 函数

    数组 数组也是一个对象,不同的是对象用字符串作为属性名,而数组用数字作为索引,数组的索引从0开始 创建数组: //方式一:构造器,可以在创建数组时指定 Var arr = new Array(1,2, ...

  3. 用C++实现俄罗斯方块(Tetris)游戏

    我是一个C++初学者,控制台实现了一个俄罗斯方块游戏. 代码如下: //"俄罗斯方块"V1.0 //李国良于2017年1月20日编写完成 #include <iostream ...

  4. cgdb | 一起边看源码边调试gdb吧

    简介 cgdb是一款轻量级的基于gdb的命令行可视化工具,关系大致如下: 尽管gdb本身可以通过layout src的命令显示源码布局,但是其功能还是过于简陋. 使用cgdb并不需要你重新去学习过多额 ...

  5. Java 多线程 - 总结概述

    概述 菜鸟教程: Java 给多线程编程提供了内置的支持. 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. 多线程是多任务的一种特别的形式,但多线程 ...

  6. [cf1528F]AmShZ Farm

    考虑$a_{i}$是"more-equal"的组合意义,有以下构造-- 有$n$个位置,每一次选择一个位置$a_{i}$,在$a_{i}$之后(包括$a_{i}$)的第一个空位上停 ...

  7. 掌握Java的内存模型,你就是解决并发问题最靓的仔

    摘要:如果编写的并发程序出现问题时,很难通过调试来解决相应的问题,此时,需要一行行的检查代码,这个时候,如果充分理解并掌握了Java的内存模型,你就能够很快分析并定位出问题所在. 本文分享自华为云社区 ...

  8. linux新增定时脚本

    crontab -e 然后新增: 0 * * * * sh /usr/local/redis/copy/redis_rdb_copy_hourly.sh 控制台回显"crontab:inst ...

  9. Electron跨平台程序破解

    1.  npm install asar -g 2. asar --version 如果有版本号就继续 3.找到需要解压的软件位置  在app.asar的地址输入 asar e app.asar tm ...

  10. 从零开始学Kotlin第三课

    kotlin函数和函数式表达式的简化写法: fun main(args:Array<String>) { var result=add(2,5) println(result) ///简化 ...