【编程思想】【设计模式】【创建模式creational】Pool

本文介绍Python中的Pool设计模式,用于管理频繁创建且成本较高的对象。通过缓存已创建的对象,减少重复创建的成本。文章提供了使用queue.Queue实现Pool的示例,并展示了如何在实际应用中复用对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值