翻墻常用的方式就是使用代理(Proxy),其基本過程如下:
瀏覽器<-->代理服務器<-->服務器
如果瀏覽器請求不到服務器,或者服務器無法響應瀏覽器,我們可以設定將瀏覽器的請求傳遞給代理服務器,代理服務器將請求轉發給服務器。然后,代理服務器將服務器的響應內容傳遞給瀏覽器。當然,代理服務器在得到請求或者響應內容的時候,本身也可以做些處理,例如緩存靜態內容以加速,或者說提取請求內容或者響應內容做些正當或者不正當的分析。這種翻墻方式,就是設計模式中代理模式(Proxy Pattern)的一個具體例子。
維基百科對代理模式做了以下解釋:
代碼如下:
In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.
基于面向過程實現的代理模式
下面是一段體現該設計模式中心的面向過程的python代碼:
代碼如下:
def hello():
print 'hi, i am hello'
def proxy():
print 'prepare....'
hello()
print 'finish....'
if __name__ == '__main__':
proxy()
運行結果:
代碼如下:
prepare....
hi, i am hello
finish....
有沒有想到裝飾器?
基于面向對象實現的代理模式
代碼如下:
class AbstractSubject(object):
def __init__(self):
pass
def request(self):
pass
class RealSubject(AbstractSubject):
def __init__(self):
pass
def request(self):
print 'hi, i am RealSubject'
class ProxySubject(AbstractSubject):
def __init__(self):
self.__rs = RealSubject()
def request(self):
self.__beforeRequest()
self.__rs.request()
self.__afterRequest()
def __beforeRequest(self):
print 'prepare....'
def __afterRequest(self):
print 'finish....'
if __name__ == '__main__':
subject = ProxySubject()
subject.request()
如果RealSubject的初始化函數init有參數,代理類ProxySubject可以作兩種方式的修改: 第一種: ProxySubject的init方法同樣也有參數,初始化代理類的時候將初始化參數傳遞給RealSubject。 第二種: 將ProxySubject的init方法改為:
新聞熱點
疑難解答