将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
应用场景:希望复用一些现存的类,但是接口又与复用环境要求不一致。
模式特点:将一个类的接口转换成为客户希望的另外一个接口。
分类:类适配器(通过多重继承)、对象适配器。
来通过例子说明,下面是用户通过适配器使用一个类的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Target: def Request(): print "common request." class Adaptee(Target): def SpecificRequest( self ): print "specific request." class Adapter(Target): def __init__( self ,ada): self .adaptee = ada def Request( self ): self .adaptee.SpecificRequest() if __name__ = = "__main__" : adaptee = Adaptee() adapter = Adapter(adaptee) adapter.Request() |
类图:
实例:
我们再来看一个简单的Adapter例子
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
#encoding=utf-8 # #by panda def printInfo(info): print unicode (info, 'utf-8' ).encode( 'gbk' ) #球员类 class Player(): name = '' def __init__( self ,name): self .name = name def Attack( self ,name): pass def Defense( self ): pass #前锋 class Forwards(Player): def __init__( self ,name): Player.__init__( self ,name) def Attack( self ): printInfo( "前锋%s 进攻" % self .name) def Defense( self ,name): printInfo( "前锋%s 防守" % self .name) #中锋(目标类) class Center(Player): def __init__( self ,name): Player.__init__( self ,name) def Attack( self ): printInfo( "中锋%s 进攻" % self .name) def Defense( self ): printInfo( "中锋%s 防守" % self .name) #后卫 class Guards(Player): def __init__( self ,name): Player.__init__( self ,name) def Attack( self ): printInfo( "后卫%s 进攻" % self .name) def Defense( self ): printInfo( "后卫%s 防守" % self .name) #外籍中锋(待适配类) #中锋 class ForeignCenter(Player): name = '' def __init__( self ,name): Player.__init__( self ,name) def ForeignAttack( self ): printInfo( "外籍中锋%s 进攻" % self .name) def ForeignDefense( self ): printInfo( "外籍中锋%s 防守" % self .name) #翻译(适配类) class Translator(Player): foreignCenter = None def __init__( self ,name): self .foreignCenter = ForeignCenter(name) def Attack( self ): self .foreignCenter.ForeignAttack() def Defense( self ): self .foreignCenter.ForeignDefense() def clientUI(): b = Forwards( '巴蒂尔' ) m = Guards( '麦克格雷迪' ) ym = Translator( '姚明' ) b.Attack() m.Defense() ym.Attack() ym.Defense() return if __name__ = = '__main__' : clientUI(); |