设计模式1-简单工厂模式

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):
        pass


class CreatFactory:
    def create_payment(self,p):
        if p == 'yue':
            return AliPay()
        elif p == 'huabei':
            return AliPay(huabei=True)
        elif p =='wechat':
            return WechatPay()
        else:
            raise TypeError('No such payment named %s' % p)


CreatFactory().create_payment('yue')

缺点:所有的对象的创建都是在一个地方

posted @ 2022-07-02 19:42  我是小菜鸡丫丫  阅读(29)  评论(0编辑  收藏  举报