python设计模式:代理模式

在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
代理模式在日常生活中很常见,比如,你去杂货店买一个插座,而不是去生产插座的工厂去买。再比如,你去访问某个网站,你并没有访问权限,但你可以通过代理去访问这个网站,然后代理再把内容传给你。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from abc import ABCMeta, abstractmethod

class FemaleA():
def __init__(self, name):
self.name = name

class Male():
__metaclass__ = ABCMeta

@abstractmethod
def send_flower(self):
pass

@abstractmethod
def send_chocolate(self):
pass

@abstractmethod
def send_book(self):
pass

class MaleA(Male):
def __init__(self, name, love_female):
self.name = name
self.love_female = FemaleA(love_female)

def send_flower(self):
print('%s送花给%s' % (self.name, self.love_female.name))

def send_chocolate(self):
print('%s送巧克力给%s' % (self.name, self.love_female.name))

def send_book(self):
print('%s送书给%s' % (self.name, self.love_female.name))

class Proxy(Male):
def __init__(self, name, proxyed_name, love_female):
self.name = name
self.proxyed = MaleA(proxyed_name, love_female)

def send_flower(self):
self.proxyed.send_flower()

def send_chocolate(self):
self.proxyed.send_chocolate()

def send_book(self):
self.proxyed.send_book()

if __name__ == '__main__':
p = Proxy('男B', '男A', '女A')
p.send_book()
p.send_chocolate()
p.send_flower()