类适配器模式,缺单是如果有多个类需要编写多个适配器类
from abc import ABCMeta, abstractmethod # 目标接口 class Payment(metaclass=ABCMeta): @abstractmethod def pay(self, money): pass class Alipay(Payment): def pay(self, money): print("zhifule %d" % money) # 待适配的类 class Bankpay(): def cost(self, monny): print("zhifule %d" % monny) # 类适配器 class PaymentAdapter(Payment, Bankpay): def pay(self, money): self.cost(money) p = PaymentAdapter() p.pay(100)
类适配器
from abc import ABCMeta, abstractmethod # 目标接口 class Payment(metaclass=ABCMeta): @abstractmethod def pay(self, money): pass class Alipay(Payment): def pay(self, money): print("alizhifule %d" % money) # 待适配的类 class Bankpay(): def cost(self, money): print("bankzhifule %d" % money) class Applypay(): def cost(self, money): print("appzhifule %d" % money) # 对象适配器, 将cost方法适配成pay方法 class PaymentAdapter(Payment): def __init__(self, payment): self.payment = payment def pay(self, money): self.payment.cost(money) p = PaymentAdapter(Applypay()) p.pay(100)