Factory Method: The Middle Child
This pattern uses a separate factory method for each object type. Each factory method is responsible for creating objects of a specific type. The Factory Method pattern provides more flexibility than the Simple Factory because it allows adding new object types without modifying the existing code.
The Factory Design Pattern is a creational pattern that allows creating objects without specifying the exact class of object that will be created. Instead, it defines an interface or an abstract class for creating objects and lets the sub-classes decide which class to instantiate.
Here’s a simple example of the Factory Design Pattern in Python:
Step 1: Define the interface or abstract class for creating objects.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
Step 2: Create concrete classes that implement the interface or abstract class.
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
Step 3: Define the factory that creates objects based on some criteria.
class AnimalFactory:
def create_animal(self, animal_type):
if animal_type == "Dog":
return Dog()
elif animal_type == "Cat":
return Cat()
else:
raise ValueError("Invalid animal type.")
Step 4: Use the factory to create objects.
factory = AnimalFactory()
dog = factory.create_animal("Dog")
print(dog.speak()) # Output: "Woof!"
cat = factory.create_animal("Cat")
print(cat.speak()) # Output: "Meow!
In this example, we defined an interface or abstract class Animal
that has a single method speak()
. We then created concrete classes Dog
and Cat
that implement this interface.
We then defined an AnimalFactory
that creates objects based on some criteria. In this case, it creates either a Dog
or a Cat
object depending on the animal_type
argument passed to the create_animal()
method.
Finally, we used the factory to create objects of type Dog
and Cat
by calling the create_animal()
method and passing the appropriate animal type as an argument.
Conclusion
This is a very basic example, but it demonstrates the key concepts of the Factory Design Pattern.