将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
应用场景:希望复用一些现存的类,但是接口又与复用环境要求不一致。
模式特点:将一个类的接口转换成为客户希望的另外一个接口。
分类:类适配器(通过多重继承)、对象适配器。
来通过例子说明,下面是用户通过适配器使用一个类的方法
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例子
#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();