设计模式-工厂模式
作者:互联网
from abc import ABCMeta, abstractclassmethod
# 接口
class Pay(metaclass=ABCMeta):
@abstractclassmethod
def pay(self, money):
pass
# 称Alipay实现了pay接口
class AliPay(Pay):
def __init__(self, huabei=False):
self.huabei = huabei
def pay(self, money):
if not self.huabei:
print("支付余额支付%d" % money)
else:
print("支付宝花呗支付%d" % money)
class WechatPay(Pay):
def pay(self, money):
print("微信支付%d" %money)
class BankPay(Pay):
def pay(self, money):
print('银行卡支付%d' % money)
# 定义一个创建支付对象的接口(一个工厂,约束具体工厂的实现)
class PaymentFacatory(metaclass=ABCMeta):
@abstractclassmethod
def creat_payment(self):
pass
class Alipayment(PaymentFacatory):
def creat_payment(self):
return AliPay()
class AlipayYuEment(PaymentFacatory):
def creat_payment(self):
return AliPay(huabei=True)
class WechatPayment(PaymentFacatory):
def creat_payment(self):
return WechatPay()
class BankPayment(PaymentFacatory):
def creat_payment(self):
return BankPay()
WechatPayment().creat_payment()
优点:
每个具体产品都对应有一个具体工厂类,不需要修改工厂类代码
隐藏了对象创建的具体实现细节
缺点:
每增加一个具体产品类,就必须增加一个相应的具体工厂类
标签:creat,money,self,模式,工厂,payment,设计模式,class,def 来源: https://www.cnblogs.com/kxtomato/p/16438436.html