python 23中设计模式 工厂模式与抽象工厂及应用场景

#https://zhuanlan.zhihu.com/p/57869247
#工厂模式
# -*- coding:utf-8 -*-

class A:

    def __init__(self):
        self.word = "运行A"

    def run(self):
        print(self.word)


class B:

    def __init__(self):
        self.word = "运行B"

    def run(self):
        print(self.word)


def Interface(classname):
    """
    工厂模式接口函数
    :param classname:
    :return:
    """
    run = dict(A=A, B=B)
    return run[classname]()


if __name__ == '__main__':
    test1 = Interface('A')
    test1.run()
    test2 = Interface('B')
    test2.run()

抽象工厂模式

# -*- coding:utf-8 -*-


class A:

    def __init__(self):
        self.word = "运行A"

    def run(self):
        print(self.word)


class B:

    def __init__(self):
        self.word = "运行B"

    def run(self):
        print(self.word)


class Interface:
    """
    抽象工厂模式接口类
    :param classname:
    :return:
    """
    def __init__(self, classname=None):
        self.test = classname

    def run(self):
        self.test().run()


if __name__ == '__main__':
    test1 = Interface()
    test1.test = A
    test1.run()
    test1.test = B
    test1.run()

    结果:
   运行A
   运行B

参考链接
#类本身就是对象的抽象,但是抽象工厂是对类的抽象,相同方法、相同属性的归并。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值