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