适配器设计模式是懒得改动某些代码,或者某些接口不方便改动的时候,使用一个特定的封装,一些特定的编写办法,使不同的接口可以使用同种调用方式使用。
更简单的说话则是,例如几个不同的接口 aliyun、qiniuyun、tencentyun是新增的接口,以前都是使用接口yun进行文件备份,现在每一种调用不同名都太烦,统一使用yun去进行aliyun、qiniuyun、tencentyun上传文件。这个时候就需要写一个适配器。
现在看一个简单例子,有一个类为Upload 是一个上传类,里面有一个方法是yun方法:
class Upload:
def yun(self):
return '...... Uploading '
之后又新增了3个上传类,分别是 AliUpload、QiniuUpload、TencentUpload,如下代码:
class AliUpload:
def aliyun(self):
return '......aliyun Uploading '
class QiniuUpload:
def qiniuyun(self):
return '......qiniuyun Uploading '
class TencentUpload:
def tencentyun(self):
return '......tencentyun Uploading '
现在我想让它们里面的yun 方法都使用统一接口名为 uploadyun,需要编写一个适配器,代码如下:
class Adapter:
def __init__(self,yun,func):
self.yun=yun
self.__dict__.update(func)
init 方法接收两个参数,一个是yun,yun是yun对象,也就是 AliUpload、QiniuUpload、TencentUpload以及Upload 的对象,还有一个是func,需要统一名称的方法字典。调用方式如下:(代码比较冗余,不过对于某一部分读者会很直观)
首先新建yun的对象:
yun_obj=Upload()
aliyun_obj=AliUpload()
qiniuyun_obj=QiniuUpload()
tencentyun_obj=TencentUpload()
随后新建适配器对象,并且把以上的对象及方法传入到适配器初始化方法中:
aptyun=Adapter(yun_obj,dict(uploadyun=yun_obj.yun))
aptali=Adapter(aliyun_obj,dict(uploadyun=aliyun_obj.aliyun))
aptqiniu=Adapter(qiniuyun_obj,dict(uploadyun=qiniuyun_obj.qiniuyun))
apttencent=Adapter(tencentyun_obj,dict(uploadyun=tencentyun_obj.tencentyun))
由于我们需要通过使用调用 uploadyun 方法名统一调用,所以键为uploadyun,之后会成为类成员变量;最后直接用适配器对象进行统一名称的方法调用:
print(aptyun.uploadyun())
print(aptali.uploadyun())
print(aptqiniu.uploadyun())
print(apttencent.uploadyun())
结果如下:
统一名称后可以再一次封装,进行统一调用(此内容不是本文内容不再赘述)。
整体代码如下:
class Upload:
def yun(self):
return '...... Uploading '
class AliUpload:
def aliyun(self):
return '......aliyun Uploading '
class QiniuUpload:
def qiniuyun(self):
return '......qiniuyun Uploading '
class TencentUpload:
def tencentyun(self):
return '......tencentyun Uploading '
class Adapter:
def __init__(self,yun,func):
self.yun=yun
self.__dict__.update(func)
#新建类
yun_obj=Upload()
aliyun_obj=AliUpload()
qiniuyun_obj=QiniuUpload()
tencentyun_obj=TencentUpload()
#适配器类
aptyun=Adapter(yun_obj,dict(uploadyun=yun_obj.yun))
aptali=Adapter(aliyun_obj,dict(uploadyun=aliyun_obj.aliyun))
aptqiniu=Adapter(qiniuyun_obj,dict(uploadyun=qiniuyun_obj.qiniuyun))
apttencent=Adapter(tencentyun_obj,dict(uploadyun=tencentyun_obj.tencentyun))
#统一接口调用示例
print(aptyun.uploadyun())
print(aptali.uploadyun())
print(aptqiniu.uploadyun())
print(apttencent.uploadyun())