Abstract Factory

The Abstract Factory pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.


class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class Bird:
    def speak(self):
        return "Tweet!"

class AnimalFactory:
    def create_dog(self):
        return Dog()
    def create_cat(self):
        return Cat()
    def create_bird(self):
        return Bird()

class Toy:
    def speak(self):
        return "Squeak!"

class Car:
    def speak(self):
        return "Vroom!"

class Truck:
    def speak(self):
        return "Honk!"

class ToyFactory:
    def create_toy(self):
        return Toy()
    def create_car(self):
        return Car()
    def create_truck(self):
        return Truck()

class AbstractFactory:
    def create_factory(self, factory_type):
        if factory_type == "Animal":
            return AnimalFactory()
        elif factory_type == "Toy":
            return ToyFactory()
        else:
            raise ValueError("Invalid factory type")

factory = AbstractFactory()
animal_factory = factory.create_factory("Animal")
toy_factory = factory.create_factory("Toy")

dog = animal_factory.create_dog()
print(dog.speak()) # Woof!
cat = animal_factory.create_cat()
print(cat.speak()) # Meow!
bird = animal_factory.create_bird()
print(bird.speak()) # Tweet!

toy = toy_factory.create_toy()
print(toy.speak()) # Squeak!
car = toy_factory.create_car()
print(car.speak()) # Vroom!
truck = toy_factory.create_truck()
print(truck.speak()) # Honk!

In this example, the AnimalFactory class and the ToyFactory class are concrete factory classes that define methods for creating specific types of objects. The AbstractFactory class is an abstract factory that has a method create_factory that returns an instance of the appropriate concrete factory class based on the value of the factory_type argument. The abstract factory can be used to create objects of different types, depending on the type of factory that is used.