设计模式之代理模式
from abc import ABCMeta,abstractmethod # -------------------------接口,用于约束 class Theme(metaclass=ABCMeta): @abstractmethod def get_content(self): pass class RealTheme(Theme): def __init__(self,filepath): self.filepath = filepath print('获取文件%s详情'%self.filepath) f = open(filepath) self.content = f.read() f.close() def get_content(self): return self.content def set_content(self,content): # f = open(self.filepath,'w') f.write(content) f.close() class ProxyA(Theme): def __init__(self,filepath): self.theme = RealTheme(filepath) def get_content(self): return self.theme.get_content() class ProxyB(Theme): # 虚代理 def __init__(self,filepath): self.filepath = filepath self.theme = None def get_content(self): # 按需分配,根据需要去创建对象,减少资源的浪费 if not self.theme: self.theme = RealTheme(self.filepath) return self.theme.get_content() class ProxyC(Theme): # 保护代理 def __init__(self,filepath): self.theme = RealTheme(filepath) def get_content(self): return self.theme.get_content() def set_content(self): # 进行权限配置,根据不同身份来配置权限控制用户的写操作 raise PermissionError # b = ProxyB('abc.txt') # print(b.get_content()) c = ProxyC('abc.txt') print(c.get_content())