• Python继承和组合 工厂模式、单例模式实现如下需求


    使用工厂模式、单例模式实现如下需求:
    (1) 电脑工厂类 ComputerFactory 用于生产电脑 Computer。工厂类使用单例模式,也就是说只能有一个工厂对象。
    (2) 工厂类中可以生产各种品牌的电脑:联想、华硕、神舟
    (3) 各种品牌的电脑使用继承实现:
    (4) 父类是 Computer 类,定义了 calculate 方法
    (5) 各品牌电脑类需要重写父类的 calculate

    继承
    class ComputerFactory:
        def __init__(self, lenovo, ASUS, HASSEE):
            self.lenovo = lenovo
            self.ASUS = ASUS
            self.HASSEE = HASSEE
    
        def createComputer(self):
            print(f"创建了电脑")
    
        def calculate(self):
            print("我是父")
    
    
    class lenovo(ComputerFactory):  # 联想
        def calcula(self):
            print("我是继承的lenovo过来的")
    
    
    class ASUS(ComputerFactory):  # 华硕
        def calcula(self):
            print("我是继承的ASUS过来的")
    
    
    class HASSEE(ComputerFactory):  # 神舟
        def calcula(self):
            print("我是继承的HASSEE过来的")
    
    
    if __name__ == '__main__':
        Computer = ComputerFactory(lenovo, ASUS, HASSEE)
        Computer.lenovo.calcula(1)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    组合
    # class ComputerFactory:
    #     def __init__(self, lenovo, ASUS, HASSEE):
    #         self.lenovo = lenovo
    #         self.ASUS = ASUS
    #         self.HASSEE = HASSEE
    #
    #     def createComputer(self):
    #         print(f"创建了电脑")
    #
    #     def calculate(self):
    #         pass
    #
    #
    # class lenovo():  # 联想
    #     def calcula(self):
    #         print("我是继承的lenovo过来的")
    #
    #
    # class ASUS():  # 华硕
    #     def calcula(self):
    #         print("我是继承的ASUS过来的")
    #
    #
    # class HASSEE():  # 神舟
    #     def calcula(self):
    #         print("我是继承的HASSEE过来的")
    #
    #
    # c = lenovo()
    # a = ASUS()
    # b = HASSEE()
    # Computer = ComputerFactory(c, a, b)
    # Computer.lenovo.calcula()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
  • 相关阅读:
    安卓 view淡入淡出(fade in fade out) kotlin
    如何熟练使用vim工具?
    云计算与大数据第12章 商用云计算平台习题带答案
    洛谷 P4408 [NOI2003] 逃学的小孩(树的直径)
    ES6 Object.assign()的用法
    【深入浅出玩转FPGA学习14----------测试用例设计2】
    【云原生】Helm 架构和基础语法详解
    文盘Rust -- 本地库引发的依赖冲突
    Cron 表达式详解及最新版本使用
    python基础 - 将子列表相同位置的元素重组
  • 原文地址:https://blog.csdn.net/weixin_49556407/article/details/125424321