2017-01-31 18 views
0

我在Python中找到了这个抽象工厂模式的例子。我试图理解为什么需要有一个DogFactory,它不会是较小的代码只是调用Dog类,有人可以解释这种模式将如何在现实世界的应用程序中有用试图使Python中的抽象工厂模式有意义

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

回答

0

通过抽象工厂模式,您可以生成特定工厂界面的实现,其中每个人都知道如何创建不同类型的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?