尝试理解Python中的抽象工厂模式

2024-04-28 23:16:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中找到了这个抽象工厂模式的例子。我想弄清楚为什么需要一个DogFactory,它不是更小的代码,只是调用Dog类,有人能解释一下这个模式在实际应用程序中是如何有用的吗

class Dog:

    def speak(self):
        return "Woof!"

    def __str__(self):
        return "Dog"


class DogFactory:

    def get_pet(self):
        return Dog()

    def get_food(self):
        return "Dog Food!"


class PetStore:

    def __init__(self, pet_factory=None):

        self._pet_factory = pet_factory


    def show_pet(self):

        pet = self._pet_factory.get_pet()
        pet_food = self._pet_factory.get_food()

        print("Our pet is '{}'!".format(pet))
        print("Our pet says hello by '{}'".format(pet.speak()))
        print("Its food is '{}'!".format(pet_food))

factory = DogFactory()

shop = PetStore(factory)

shop.show_pet()

Tags: selfformatgetreturnfoodfactorydef模式
2条回答

我知道另一个网站有更好的解释,也有许多不同编程语言的示例代码,包括Python。在

https://refactoring.guru/design-patterns/abstract-factory/python/example#lang-features

玩得开心!在

使用抽象工厂模式,您可以生成特定工厂接口的实现,每个实现都知道如何创建不同种类的dog()。抽象工厂的方法被实现为工厂方法。抽象工厂模式和工厂方法模式通过抽象类型和工厂将客户机系统与实际实现类分离。在

看这些参考资料链接:-在

  1. http://www.dofactory.com/net/abstract-factory-design-pattern#_self2
  2. What is the basic difference between the Factory and Abstract Factory Patterns?

相关问题 更多 >