"""
简单工厂模式不是23中设计模式中的,但是必须要知道。简单工厂模式不直接向客户端暴露对象创建的细节,而是通过一个工厂类来负责
创建产品类的实例。简单工程模式的角色有:工厂角色、抽象产品角色、具体产品角色,通过例子来加深理解:
"""
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("花呗支付了{0}".format(money)) else: print("支付宝支付了{0}".format(money)) # 产品角色 class WechatPay(Payment): def pay(self, money): print("微信支付了{0}".format(money)) # 工厂类角色 class PaymentFactory(object): def create_payment(self, method): print(method) if method == 'Alipay': return Alipay() elif method == "WechatPay": return WechatPay() elif method == "HuabeiPay": return Alipay(use_huabei=True) else: raise TypeError('No such payment named %s' % method) pf = PaymentFactory() pf.create_payment("Alipay").pay("100") a = Alipay()
工厂模式
from abc import ABCMeta, abstractmethod # 抽象产品 class PayMent(metaclass=ABCMeta): @abstractmethod def pay(self, money): pass # 具体产品 class AlipayMent(PayMent): def __init__(self, use_huabei=False): self.use_huabei = use_huabei def pay(self, money): if self.use_huabei: print("huawei支付{}".format(money)) else: print("alipay支付{}".format(money)) class WechatMent(PayMent): def pay(self, money): print("wechat支付{}".format(money)) # 抽象工厂 class PayMentFactory(metaclass=ABCMeta): @abstractmethod def create_payment(self): pass # 具体工厂角色 class AlipayFactory(PayMentFactory): def create_payment(self): return AlipayMent() class WechatFactory(PayMentFactory): def create_payment(self): return WechatMent() class HuabeiFactory(PayMentFactory): def create_payment(self): return AlipayMent(use_huabei=True) A = HuabeiFactory().create_payment() A.pay('100')