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

yipeiwu_com6年前Python基础

将一个类的接口转换成客户希望的另外一个接口。使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
应用场景:希望复用一些现存的类,但是接口又与复用环境要求不一致。

模式特点:将一个类的接口转换成为客户希望的另外一个接口。

分类:类适配器(通过多重继承)、对象适配器。

来通过例子说明,下面是用户通过适配器使用一个类的方法

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

类图:

201632112018391.jpg (669×296)

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

相关文章

python scrapy重复执行实现代码详解

这篇文章主要介绍了python scrapy重复执行实现代码详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Scrapy是一个为了...

python中字符串内置函数的用法总结

capitalize() 首字母大写 a='someword' b=a.capitalize() print(b) —>Someword casefold()&l...

用Python代码来绘制彭罗斯点阵的教程

用Python代码来绘制彭罗斯点阵的教程

这里是显示彭罗斯点阵的Python的脚本。是的,这是可以运行的有效Phython代码。 译注:彭罗斯点阵,物理学术语。上世纪70年代英国数学家彭罗斯第一次提出了这个概念,称为彭罗斯点阵(...

对dataframe进行列相加,行相加的实例

实例如下所示: >>> import pandas as pd >>> df = pd.DataFrame({"x":['a','b','c','...

Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度

Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度

前言 matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作。每个pyplot函数对一幅图片(figure)做一些改动:比如创...