工厂模式

来源:互联网 发布:控制鼠标的软件 编辑:程序博客网 时间:2024/05/17 02:49

1、简单工厂模式

class Cat:    def eat(self):        print('猫在吃东西!!')class Dog:    def eat(self):        print('狗在吃东西!!')class Human:    def eat(self):        print('人在吃东西!!')class Factory:    def create(self,name):        f = None        if name == 'dog':            f = Dog()        elif name == 'cat':            f = Cat()        elif name == 'human':            f = Human()        return fdef main():    f1 = Factory()    f2 = f1.create('dog')    f2.eat()    f3 = f1.create('cat')    f3.eat()main()

2、抽象工厂模式

class Cat:    def eat(self):        print('猫在吃东西!!')class Dog:    def eat(self):        print('狗在吃东西!!')class PetShop:    def __init__(self,animal):        self.animal = animal    def show(self):        pet = self.animal.create()        pet.eat()class DogCreate:    def create(self):        return Dog()class CatCreate:    def create(self):        return Cat()def main():    f1 = DogCreate()    f2 = CatCreate()    pet1 = PetShop(f1)    pet2 = PetShop(f2)    pet1.show()    pet2.show()main()


原创粉丝点击