抽象工厂模式(Abstract Factory)属于创建型工厂模式的一种。
特点:客户仅与抽象类定义的接口交互,而不使用特定的具体类的接口。
这里是一个python的例子,运行环境是python 2.7
import random
class PetShop:
"""A pet shop"""
def __init__(self, animal_factory=None):
self.pet_factory = animal_factory
def show_pet(self):
"""Create and show a pet using the abstract factory"""
pet = self.pet_factory.get_pet()
print("This is a lovely", pet)
print("It says", pet.speak())
print("It eats", self.pet_factory.get_food())
class Dog:
def speak(self):
return "woof"
def __str__(self):
return "Dog"
class Cat:
def speak(self):
return "meow"
def __str__(self):
return "Cat"
# Factory classes
class DogFactory:
def get_pet(self):
return Dog()
def get_food(self):
return "dog food"
class CatFactory:
def get_pet(self):
return Cat()
def get_food(self):
return "cat food"
def get_factory():
"""Let's be dynamic!"""
return random.choice([DogFactory, CatFactory])()
if __name__ == "__main__":
factory = PetShop(get_factory())
for i in range(3):
factory.show_pet()
print("="*20)
这里主要是对抽象工厂进行简单的学习。
这里主要是通过get_factory函数来进行工厂的选择。同时每个真实对象都对应一个工厂类的方式构建
在每个新对象创建的时候都要重新定义一个工厂类,这样使用抽象工厂增加了类的数量,对工程的构建中类的数量带来一定的麻烦。