【编程思想】【设计模式】【创建模式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转载版
原文地址:https://www.cnblogs.com/demonzk/p/9035336.html