设计模式-抽象工厂模式-abstractfactory-python

时间:2022-09-08 20:27:05

def

为创建一组相关或相互依赖的对象提供一个接口, 而且无须指定它们的具体类。

usage

封装性。每个产品的实现类不是高层模块要关心的, 只要知道工厂类是谁, 我就
能创建出一个需要的对象, 省时省力, 优秀设计就应该如此。

产品族内的约束为非公开状态。 生产过程对调用工厂类的高层模块来说是透明的, 它不需要知道这个约束, 具体的产品族内的约束是在工厂内实现的。

attention

抽象工厂模式的最大缺点就是产品族扩展非常困难。

抽象工厂模式的使用场景定义非常简单: 一个对象族(或是一组没有任何关系的对象)都有相同的约束, 则可以使用抽象工厂模式。

code

class PetShop(object):

"""A pet shop"""

def __init__(self, animal_factory=None):
"""pet_factory is our abstract factory. We can set it at will."""

self.pet_factory = animal_factory

def show_pet(self):
"""Creates and shows a pet using the abstract factory"""

pet = self.pet_factory.get_pet()
print("We have a lovely {}".format(pet))
print("It says {}".format(pet.speak()))
print("We also have {}".format(self.pet_factory.get_food()))


# Stuff that our factory makes

class Dog(object):

def speak(self):
return "woof"

def __str__(self):
return "Dog"


class Cat(object):

def speak(self):
return "meow"

def __str__(self):
return "Cat"


# Factory classes

class DogFactory(object):

def get_pet(self):
return Dog()

def get_food(self):
return "dog food"


class CatFactory(object):

def get_pet(self):
return Cat()

def get_food(self):
return "cat food"


# Create the proper family
def get_factory():
"""Let's be dynamic!"""
return random.choice([DogFactory, CatFactory])()


# 抽象工厂在这里!!!
@six.add_metaclass(abc.ABCMeta)
class Pet(object):

@classmethod
def from_name(cls, name):
for sub_cls in cls.__subclasses__():
if name == sub_cls.__name__.lower():
return sub_cls()

@abc.abstractmethod
def speak(self):
""""""


class Kitty(Pet):
def speak(self):
return "Miao"


class Duck(Pet):
def speak(self):
return "Quak"


# Show pets with various factories
if __name__ == "__main__":
for i in range(3):
shop = PetShop(get_factory())
shop.show_pet()
print("=" * 20)

for name0 in ["kitty", "duck"]:
pet = Pet.from_name(name0)
print("{}: {}".format(name0, pet.speak()))

### OUTPUT ###
# We have a lovely Cat
# It says meow
# We also have cat food
# ====================
# We have a lovely Dog
# It says woof
# We also have dog food
# ====================
# We have a lovely Cat
# It says meow
# We also have cat food
# ====================
# kitty: Miao
# duck: Quak