-
內(nèi)容:為其他對(duì)象提供一種代理一控制對(duì)這個(gè)對(duì)象的訪問
-
應(yīng)用場(chǎng)景:
- 遠(yuǎn)程代理: 為遠(yuǎn)程的對(duì)象提供代理
- 虛代理:根據(jù)需要?jiǎng)?chuàng)建很大的對(duì)象
- 保護(hù)代理:控制對(duì)原始對(duì)象的訪問,用于對(duì)象有不同訪問權(quán)限時(shí)
-
UML圖
文章來源:http://www.zghlxwxcb.cn/news/detail-619101.html
-
舉個(gè)例子:
需求:完成一個(gè)文件讀取和寫入,完成遠(yuǎn)程代理、需代理、保護(hù)代理。文章來源地址http://www.zghlxwxcb.cn/news/detail-619101.html
from abc import ABCMeta,abstractmethod
# 代理抽象類
class Subject(metaclass=ABCMeta):
@abstractmethod
def get_content(self):
pass
@abstractmethod
def set_content(self,content):
pass
# 遠(yuǎn)程代理
class RealSubject(Subject):
def __init__(self,filename):
self.filename=filename
f=open(filename,'r',encoding='utf-8')
print(f)
print("讀取文件內(nèi)容")
self.content=f.read()
f.close()
def get_content(self):
return self.content
def set_content(self, content):
f=open(self.filename,'w')
f.write(content)
f.close()
# 虛代理
class VirtualProxy(Subject):
def __init__(self,filename):
self.filename=filename
self.subj=None
def get_content(self):
if not self.subj:
self.subj=RealSubject(self.filename)
def set_content(self,content):
if not self.subj:
self.subj = RealSubject(self.filename)
return self.subj.set_content(content)
# 保護(hù)代理
class ProtectedProxy(Subject):
def __init__(self,filename):
self.subj=RealSubject(filename)
def get_content(self):
return self.subj.get_content()
def set_content(self, content):
raise PermissionError("無寫入權(quán)限")
# 遠(yuǎn)程代理
subj=RealSubject('../test.txt')
# 虛擬代理
vir=VirtualProxy('../test.txt')
vir.get_content()
vir.set_content("寫入文本內(nèi)容")
# 保護(hù)代理
protect=ProtectedProxy('../test.txt')
protect.get_content()
protect.set_content("寫入文件")
- 優(yōu)點(diǎn):
- 遠(yuǎn)程代理:可以隱藏對(duì)象位于遠(yuǎn)程地址空間的事實(shí)
- 虛代理:可以進(jìn)行優(yōu)化,例如根據(jù)要求創(chuàng)建對(duì)象
- 保護(hù)代理:允許在訪問一個(gè)對(duì)象時(shí)有一些附加的內(nèi)務(wù)處理
到了這里,關(guān)于10.python設(shè)計(jì)模式【代理模式】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!