zoukankan      html  css  js  c++  java
  • 设计模式之工厂模式代码

    Animal是父类,Dog和Cat继承父类,然后创建一个工厂类,通过静态方法来设置匹配规则,
    同样的示例化方式和调用方式,根据传入的内容的不同,结果也不一样。

    class Animal:
        def __init__(self, name):
            self.__name = name
    
        def getName(self):
            return self.__name
    
    
    class Dog(Animal):
        def __init__(self, name):
            super().__init__(name)
    
        def getName(self):
            return "dog"
    
    
    class Cat(Animal):
        def __init__(self, name):
            super().__init__(name)
    
        def getName(self):
            return "cat"
    
    
    class AnimailMake:
        @staticmethod
        def makeanimial(name):
            am = None
            if name == "cat":
                am = Cat(name)
            elif name == "dog":
                am = Dog(name)
            else:
                am = Animal(name)
            return am
    
    
    if __name__ == '__main__':
        am = AnimailMake.makeanimial("cat")
        print(am.getName())
        am = AnimailMake.makeanimial("dog")
        print(am.getName())
        am = AnimailMake.makeanimial("?")
        print(am.getName())
    
    
  • 相关阅读:
    Nginx + uWSGI 配置django
    django视图缓存的实现
    scrapy 资料
    scrapy 安装
    程序题做题一般步骤
    检查代码的一般步骤
    Mathematical-Analysis-I-4
    Mathematical-Analysis-I-3
    Mathematical-Analysis-I-1
    Mathematical-Analysis-I-2
  • 原文地址:https://www.cnblogs.com/c-x-a/p/10950863.html
Copyright © 2011-2022 走看看