1. 工厂模式
from abc import ABCMeta, abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def __init__(self, use_huabei=False):
self.use_huabei = use_huabei
def pay(self, money):
if self.use_huabei:
print("使用花呗支付 %d " % money)
else:
print("Ali payed %d" % money)
class WechatPay(Payment):
def pay(self, money):
print("Wechat pay %d" % money)
class PaymentFactory(metaclass=ABCMeta):
@abstractmethod
def create_payment(self):
pass
class AliPayFactory(PaymentFactory):
def create_payment(self):
return Alipay()
class WechatPayFactory(PaymentFactory):
def create_payment(self):
return WechatPay()
class HuabeiPayFactory(PaymentFactory):
def create_payment(self):
return Alipay(use_huabei=True)
if __name__ == '__main__':
pf = HuabeiPayFactory()
p = pf.create_payment()
p.pay(100)
假设需要增加一种支付方式 银联支付
则需要 增加两个类 BankPay BankPayFactory
from abc import ABCMeta, abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def __init__(self, use_huabei=False):
self.use_huabei = use_huabei
def pay(self, money):
if self.use_huabei:
print("使用花呗支付 %d " % money)
else:
print("Ali payed %d" % money)
class WechatPay(Payment):
def pay(self, money):
print("Wechat pay %d" % money)
class BankPay(Payment):
def pay(self, money):
print("银联支付 pay %d" % money)
class PaymentFactory(metaclass=ABCMeta):
@abstractmethod
def create_payment(self):
pass
class AliPayFactory(PaymentFactory):
def create_payment(self):
return Alipay()
class WechatPayFactory(PaymentFactory):
def create_payment(self):
return WechatPay()
class HuabeiPayFactory(PaymentFactory):
def create_payment(self):
return Alipay(use_huabei=True)
class BankPayFactory(PaymentFactory):
def create_payment(self):
return BankPay()
if __name__ == '__main__':
pf = BankPayFactory()
p = pf.create_payment()
p.pay(100)
对于与每个 具体的产品类 (WechatPay AliPay BankPay) 必须增加 相应的 工厂类 (WechatPayFactory AliPayFactory BankPayFactory)