Python Design Patterns 简明教程
Python Design Patterns - Proxy
代理设计模式包括一个新对象,该对象代替现有的称为“真实主题”的对象,称为“代理”。创建真实主题的代理对象必须在同一个界面中,以至于客户端不应该有任何想法,即代理用于代替真实对象。客户端向代理发出的请求将通过真实主题传递。
代理模式的 UML 表示如下 -
How to implement the proxy pattern?
现在让我们看看如何实现代理模式。
class Image:
def __init__( self, filename ):
self._filename = filename
def load_image_from_disk( self ):
print("loading " + self._filename )
def display_image( self ):
print("display " + self._filename)
class Proxy:
def __init__( self, subject ):
self._subject = subject
self._proxystate = None
class ProxyImage( Proxy ):
def display_image( self ):
if self._proxystate == None:
self._subject.load_image_from_disk()
self._proxystate = 1
print("display " + self._subject._filename )
proxy_image1 = ProxyImage ( Image("HiRes_10Mb_Photo1") )
proxy_image2 = ProxyImage ( Image("HiRes_10Mb_Photo2") )
proxy_image1.display_image() # loading necessary
proxy_image1.display_image() # loading unnecessary
proxy_image2.display_image() # loading necessary
proxy_image2.display_image() # loading unnecessary
proxy_image1.display_image() # loading unnecessary