Python: Proxy Pattern
DuProxy.py
# 代理模式 Proxy Pattern
from abc import ABCMeta, abstractmethod
import abc
import random
class ISubject(metaclass=ABCMeta):
"An interface implemented by both the Proxy and Real Subject"
@staticmethod
@abstractmethod
def request():
"A method to implement"
class RealSubject(ISubject):
"The actual real object that the proxy is representing"
def __init__(self):
# hypothetically enormous amounts of data
self.enormous_data = [1, 2, 3,'geovindu','Geovin Du','涂聚文']
def request(self):
return self.enormous_data
class Proxy(ISubject):
"""
The proxy. In this case the proxy will act as a cache for
`enormous_data` and only populate the enormous_data when it
is actually necessary
"""
def __init__(self):
self.enormous_data = []
self.real_subject = RealSubject()
def request(self):
"""
Using the proxy as a cache, and loading data into it only if
it is needed
"""
if self.enormous_data == []:
print("从真实主体提取数据")
self.enormous_data = self.real_subject.request()
return self.enormous_data
print("从代理缓存中提取数据")
return self.enormous_data
class AbstractClass(metaclass=abc.ABCMeta):
""" interface for real and proxy object """
@abc.abstractmethod
def sort_digits(self, reverse=False):
pass
class RealClass(AbstractClass):
""" RealClass that holds a larger object """
def __init__(self):
self.digits = []
for i in range(1000000):
self.digits.append(random.random())
def sort_digits(self, reverse=False):
self.digits.sort()
if reverse:
self.digits.reverse()
class ProxyClass(AbstractClass):
""" A proxy class that has the same interface as RealClass. """
ref_count = 0
def __init__(self):
""" Creates an object if it doesn't exist and caches it otherwise """
if not getattr(self.__class__, '缓存对象', None):
self.__class__.cached_object = RealClass()
print('生成新对象')
else:
print('使用缓存的对象')
self.__class__.ref_count += 1
print('引用计数:', self.__class__.ref_count)
def sort_digits(self, reverse=False):
print('排序方法')
print(locals().items())
# invokes the sort_digits method of real class
self.__class__.cached_object.sort_digits(reverse=reverse)
def __del__(self):
""" Delete the object when the number of reference is 0 """
self.__class__.ref_count -= 1
if self.__class__.ref_count == 0:
print('删除缓存对象')
del self.__class__.cached_object
print('引用计数:', self.__class__.ref_count)
main.py 调用
# 代理模式 Proxy Pattern
duSubject = DuProxy.Proxy()
# use SUBJECT
print(id(duSubject))
# load the enormous amounts of data because now we want to show it.
print(duSubject.request())
# show the data again, but this time it retrieves it from the local cache
print(duSubject.request())
print("\n")
proxA = DuProxy.ProxyClass()
print()
proxB = DuProxy.ProxyClass()
print()
proxC = DuProxy.ProxyClass()
print()
proxA.sort_digits(reverse=True)
print()
print('删除对象 proxA')
del proxA
print('删除对象 proxB')
del proxB
print('删除对象 proxC')
del proxC
输出:
1830765068000
从真实主体提取数据
[1, 2, 3, 'geovindu', 'Geovin Du', '涂聚文']
从代理缓存中提取数据
[1, 2, 3, 'geovindu', 'Geovin Du', '涂聚文']
生成新对象
引用计数: 1
生成新对象
引用计数: 2
生成新对象
引用计数: 3
排序方法
dict_items([('self', <DuProxy.ProxyClass object at 0x000001AA4219FFA0>), ('reverse', True)])
删除对象 proxA
引用计数: 2
删除对象 proxB
引用计数: 1
删除对象 proxC
删除缓存对象
引用计数: 0




哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号