设计模式之适配器

设计模式之适配器模式(主要是将不符合规则的接口通过一定手段使其适配而符合规则,隐藏具体适配细节):

from abc import abstractmethod,ABCMeta
class Payment(metaclass=ABCMeta):
    # 支付接口类
    @abstractmethod
    def pay(self,money):
        pass
    
    
   
# -----------符合规则的支付类------------
class Alipay(Payment):
    # 符合规则的支付方法
    def pay(self,money):
        print('使用阿里支付%s元'%money)
class Applepay(Payment):
    def pay(self,money):
        print('使用苹果支付%s元'%money)



# -----------不符合规则的支付类(也即待适配类)------------
class Wechatpay:
    # 待适配类
    def zhifu(self,money):
        print('使用微信支付%s元'%money)
class Unionpay:
    # 待适配类
    def yinlianpay(self,money):
        print('使用银联支付%s元'%money)




# --------进行适配(使用类适配器进行适配)------------
class WechatRealpay(Payment,Wechatpay):
    # 类适配器
    def pay(self,money):
        return self.zhifu(money)
class UnionRealpay(Payment,Unionpay):
    # 类适配器
    def pay(self,money):
        return self.yinlianpay(money)




# -----------进行适配(使用对象适配器进行适配)------------
class WechatPayAdapter(Wechatpay):
    # 对象适配器
    def __init__(self,payment=Wechatpay()):
        # 这个适配器是为微信做的,默认让其支付方式为微信支付
        self.payment = payment
    def pay(self,money):
        return self.payment.zhifu(money)
class UnionPayAdapter(Unionpay):
    def __init__(self,payment=Unionpay()):
        # 这个对象适配器是为银联支付做的,默认让其支付方式为银联支付
        self.payment = payment
    def pay(self,money):
        return self.payment.yinlianpay(money)




# ----------创建一个支付工厂用于测试使用------------
class Factory:
    # 工厂类用于测试适配器
    @classmethod
    def create_payment(cls,method):
        if method == 'ali':
            return Alipay()
        elif method == 'apple':
            return Applepay()
        elif method == 'wechat':
            # 注意这里调用的是真是的支付类,即已经适配完成的类
            # return WechatRealpay()#类适配器
            return WechatPayAdapter()#对象适配器
        elif method == 'yinlian':
            # return UnionRealpay()
            return UnionPayAdapter()
        else:
            raise NameError(method)
        
        
# 测试
# payment = Factory.create_payment('wechat')
payment = Factory.create_payment('yinlian')
payment.pay(50)

猜你喜欢

转载自www.cnblogs.com/aadmina/p/8975369.html