I've looked up design patterns in python and saw a the following sentence in some article:
"We implement our Abstract Factory without using inheritance, mainly because Python is a dynamically typed language and therefore does not require abstract classes."
Code example:
class Dog:
"""One of the objects to be returned"""
def speak(self):
return "Woof!"
def __str__(self):
return "Dog"
class DogFactory:
"""Concrete Factory"""
def get_pet(self):
"""Returns a Dog object"""
return Dog()
def get_food(self):
"""Returns a Dog Food object"""
return "Dog Food!"
class PetStore:
""" PetStore houses our Abstract Factory """
def __init__(self, pet_factory=None):
""" pet_factory is our Abstract Factory """
self._pet_factory = pet_factory
def show_pet(self):
""" Utility method to display the details of the objects retured by the DogFactory """
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))
#Create a Concrete Factory
factory = DogFactory()
#Create a pet store housing our Abstract Factory
shop = PetStore(factory)
#Invoke the utility method to show the details of our pet
shop.show_pet()
I understand the example I provided, but I don't get this statement, and I've seen so many other examples implementing design patterns in python using inheritance and abstract classes (e.g.: the abstract factory in this case) like how almost every other languages do such as java.
I would really appreciate an explanation on the statement and how the two approaches (with/without abstract classes or inheritance) differ using code examples.
Thank you.
Aucun commentaire:
Enregistrer un commentaire