python 设计模式-适配器模式_Python设计模式编程中Adapter适配器模式的使用实例

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()

类图:

b7965f72e1fe0cede254270999b02be9.png

实例:

我们再来看一个简单的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();

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值