工厂模式之简单工厂模式

# 示例
在下面的代码中我们将创建一个名为Animal的抽象产品。Animal是一个抽象的基类(ABCMeta是Python的特殊元素,用来生成类的Abstract),它带有方法do_say().我们利用Animal接口创建了两种产品(Cat和Dog),并实现了do_say()方法来提供这些动物的相应的叫声。ForestFactory是一个带有make_sound()方法的工厂。根据客户端传递的参数类型,它就可以在运行时创建适当的Animal实例,并输出正确的声音

from abd import ABCMeat,abstractmethod

class Animal(metaclass=ABCMeta):
    @abstractmethod
    def do_say(self):
        pass

class Dog(Aniaml):
    def do_say(self):
        print("Bhow Bhow!!")
        
class Cat(Animal):
    def do_say(self):
        print("Meow Meow!!")
        
class ForestFactory(object):
    def make_sound(self, object_type):
        return eval(object_type)().do_say()

if __name__ == '__main__':
	ff = ForestFactory()
    animal = input("which animal should make_sound Dog or Cat?")
    ff.make_sound(animal)
posted @ 2022-01-27 15:13  我在路上回头看  阅读(30)  评论(0编辑  收藏  举报