1 概述
适配器是结构型模式的一种,结构型模式主要控制几个类组成什么结构。
VGA->HDMI
Type-C->micro
本来不同的接口可以通过适配器进行链接
角色
- 目标接口 Payment
- 待适配的类 BankPay、ApplePay
- 适配器 NewBankPay PaymentAdapter
场景
想使用一个已经实现的类,但是接口不符合你的要求
对象适配器,使用组合的方式,将已经实现的类的对象传给对象适配器,对象适配器也要实现目标接口,接口方法实现对象的某个方法。
2 代码实现
2.1 一个类不符合接口
假设某公司的支付系统有两个不同的版本,两个不同的版本分别使用不同的接口实现,高层代码调用就会比较麻烦
from abc import ABCMeta, abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class AliPay(Payment):
def pay(self, money):
print('Alipay %d' % money)
class WechatPay(Payment):
def pay(self, money):
print('Wechat pay %d' % money)
class BankPay:
def cost(self, money):
print('bank pay %d' % money)
p = AliPay()
p.pay(100)
p = BankPay()
p.pay(101)
"""
OUT:
Alipay 100 AliPay实现了Payment接口,有pay方法
AttributeError: 'BankPay' object has no attribute 'pay' BankPay没有实现Payment接口,没有pay方法会报错
如果把cost改成pay,那么另一套系统的调用就会报错
"""
适配器(类适配器)
class NewBankPay(Payment,BankPay):
"""
继承Payment接口和BankPay类
Payment接口约束了必须实现pay方法
BankPay父类的作用是可以直接让子类使用它的cost()方法
"""
def pay(self, money):
self.cost(money)
p = NewBankPay()
p.pay(101) # bank pay 101
2.2 多个类不符合接口
如果不只是一个类
如果两个类甚至多个类,都实现了cost方法,那么我难道要写多个新适配器类?
class ApplePay:
def cost(self, money):
print('apply pay %d' %money)
class BankPay:
def cost(self, money):
print('bank pay %d' % money)
升级版适配器(对象适配器)
面向对象中复用代码有两种方式,一种是继承,另一种是组合(一个类中放另一个类的对象)
class PaymentAdapter(Payment):
def __init__(self,payment):
self.payment = payment
def pay(self, money):
self.payment.cost(money)
p = PaymentAdapter(ApplePay())
p.pay(101)
p = PaymentAdapter(BankPay())
p.pay(102)
"""
OUT:
apply pay 101
bank pay 102
"""