代理模式

模式说明

代理模式就是给一个对象提供一个代理,并由代理对象控制对原对象的引用。

在代理模式中,“第三者”代理主要是起到一个中介的作用,它连接客户端和目标对象。

模式结构图

程序示例

说明:男孩给女孩送礼物,通过她的闺蜜来代理完成

代码:

 1 class Girl(object):
 2     def __init__(self,name):
 3         self._name = name
 4 
 5 class Gift(object):
 6     def __init__(self,girl):
 7         self._target = girl
 8     def GiveChocolate(self):
 9         pass
10     def GiveFlower(self):
11         pass
12 
13 class Boy(Gift):
14     def __init__(self, name, girl):
15         self._name=name
16         super(Boy, self).__init__(girl)
17 
18     def GiveChocolate(self):
19         print '%s gives %s a chocolate' %(self._name,self._target._name)
20         
21     def GiveFlower(self):
22         print '%s gives %s a flower' %(self._name,self._target._name)
23 
24 class ChumProxy(Gift):
25     def __init__(self,boy):
26         self._boy = boy
27 
28     def GiveChocolate(self):
29         self._boy.GiveChocolate()
30     def GiveFlower(self):
31         self._boy.GiveFlower()    
32 
33 if __name__=='__main__':
34     girl = Girl('girl')
35     boy = Boy('boy',girl)
36     chum = ChumProxy(boy)
37     chum.GiveChocolate()
38     chum.GiveFlower()

运行结果:

参考来源:

http://www.cnblogs.com/chenssy/p/3679190.html

http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html

http://www.cnblogs.com/Terrylee/archive/2006/07/17/334911.html

原文地址:https://www.cnblogs.com/cotton/p/3931331.html