学习--python设计模式((二十二)【连接池模式】)

#-*-coding:utf-8-*-

classQueueObject():

def__init__(self,queue,auto_get=False):

self._queue=queue

self.object=self._queue.get()ifauto_getelseNone

def__enter__(self):

ifself.objectisNone:

self.object=self._queue.get()

returnself.object

def__exit__(self,Type,value,traceback):

ifself.objectisnotNone:

self._queue.put(self.object)

self.object=None

def__del__(self):

ifself.objectisnotNone:

self._queue.put(self.object)

self.object=None

defmain():

try:

importqueue

exceptImportError:#python2.x的兼容性

importQueueasqueue

deftest_object(queue):

queue_object=QueueObject(queue,True)

print('内部func:{}'.format(queue_object.object))

sample_queue=queue.Queue()

sample_queue.put('yam')

withQueueObject(sample_queue)asobj:

print('Insidewith:{}'.format(obj))

print('Outsidewith:{}'.format(sample_queue.get()))

sample_queue.put('sam')

test_object(sample_queue)

print('外部func:{}'.format(sample_queue.get()))

ifnotsample_queue.empty():

print(sample_queue.get())

if__name__=='__main__':

main()

相关推荐