工厂方法模式
提示:这里可以添加本文要记录的大概
内容: 定义一个用于创建对象的接口(工厂接口), 让子类决定实例化哪一个产品类;
角色:
抽象工厂角色; 抽象类; 具体工厂角色: 具体类;
抽象产品: 接口(抽象方法); 具体产品角色: 具体类中对应接口的实现方法;
提示:以下是本篇文章正文内容,下面案例可供参考
1.底层代码
from abc import ABCMeta, abstractmethod
class Payment(metaclass= ABCMeta ):
# abstract class
@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("huabei paid : %d RMB" % money)
else:
print("Alipay paid: %d RMB" % money)
class WechatPay(Payment):
def pay(self, money):
print("Wechat paid: %d RMB" % money)
class BankPay(Payment):
def pay(self, money):
print(" Bank paid: %d RMB" % 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 HuabeiFactory(PaymentFactory):
def create_payment(self):
return Alipay(use_huabei= True )
class BankFactory(PaymentFactory):
def create_payment(self):
return BankPay()
2. 高层代码
代码如下(示例):
# client use , high level code
pf = WechatPayFactory()
p = pf.create_payment()
p.pay(1000)
该处使用的url网络请求的数据。
总结
提示:这里对文章进行总结: