设计模式之工厂模式代码

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())

posted @ 2019-05-30 17:25  公众号python学习开发  阅读(221)  评论(0编辑  收藏  举报