代理模式
概述
对象
- 抽象实体(Subject)
- 实体(RealSubject)
- 代理(Proxy)
适用场景
- 远程代理:为远程对象提供代理
- 虚代理:根据需要创建很大的对象
- 保护代理:控制对原始对象的访问,用于对象有不同访问对象时
例子
from abc import ABCMeta, abstractmethod
class FileInterface(metaclass=ABCMeta):
@abstractmethod
def write(self, content):
pass
@abstractmethod
def read(self):
pass
class File(FileInterface):
def __init__(self, name):
self.name = name
with open(self.name, mode='a+', encoding='utf-8') as fi:
self.content = fi.read()
def write(self, content):
with open(self.name, 'w', encoding='utf-8') as fi:
fi.write(content)
def read(self):
with open(self.name, 'r', encoding='utf-8') as fi:
return fi.read()
class VirtualProxy(FileInterface):
def __init__(self, name):
self.name = name
self.file_proxy = None
def write(self, conrent):
if not self.file_proxy:
self.file_proxy = File(self.name)
return self.file_proxy.write(conrent)
def read(self):
if not self.file_proxy:
self.file_proxy = File(self.name)
return self.file_proxy.read()
class ProtectProxy(FileInterface):
def __init__(self, name):
self.name = name
self.file_proxy = File(self.name)
def write(self, conrent):
raise Exception("没有写权限")
def read(self):
return self.file_proxy.read()
print("虚代理")
virtual_proxy = VirtualProxy('test.txt')
print('创建时不会创建file obj')
print('写入')
virtual_proxy.write('testing ...')
print('读取')
print(virtual_proxy.read())
print("保护代理")
protect_proxy = ProtectProxy('test.txt')
print('读取')
print(protect_proxy.read())
print('写入')
protect_proxy.write('testing ...')
优点
- 远程代理:可以隐藏对象位于远程地址的事实
- 虚代理:可以进行优化,例如根据需求创建对象
- 保护代理:允许在访问一个对象是存在一些附加的业务处理