Factory Pattern
The Factory pattern is a creational design pattern that provides an interface
for creating objects in a super class, but allows subclasses to
alter the type of objects that will be created.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
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")
factory = AnimalFactory()
dog = factory.create_animal("Dog")
print(dog.speak()) # Woof!
cat = factory.create_animal("Cat")
print(cat.speak()) # Meow!
In this example, the Animal class is the superclass and the Dog and Cat classes are subclasses that inherit from Animal. The AnimalFactory class is the factory class that has a method create_animal that takes an animal_type argument and returns an instance of the corresponding class. The factory method can be used to create objects of different types, depending on the value of the animal_type argument.