Sobes.tech
Junior — Middle

Explain the differences between Factory Method and Abstract Factory patterns, their main differences, and use cases.

sobes.tech AI

Answer from AI

Factory Method is a pattern that defines an interface for creating an object but allows subclasses to decide which class to instantiate. It is used when object creation needs to be delegated to subclasses to increase flexibility and extensibility.

Abstract Factory is a pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is useful when creating a set of related objects that must work together.

Main differences:

  • Factory Method creates a single product, Abstract Factory creates a family of products.
  • Factory Method is usually implemented through inheritance, Abstract Factory through composition.

Use cases:

  • Factory Method: when there is a hierarchy of products and creation needs to be delegated to subclasses.
  • Abstract Factory: when creating families of related objects ensuring their compatibility.

Example of Factory Method in Python:

from abc import ABC, abstractmethod

class Product(ABC):
    @abstractmethod
    def operation(self):
        pass

class ConcreteProductA(Product):
    def operation(self):
        return "Result of ConcreteProductA"

class Creator(ABC):
    @abstractmethod
    def factory_method(self):
        pass

    def some_operation(self):
        product = self.factory_method()
        return product.operation()

class ConcreteCreatorA(Creator):
    def factory_method(self):
        return ConcreteProductA()

creator = ConcreteCreatorA()
print(creator.some_operation())  # Output: Result of ConcreteProductA

Example of Abstract Factory in Python:

from abc import ABC, abstractmethod

class AbstractProductA(ABC):
    @abstractmethod
    def useful_function_a(self):
        pass

class AbstractProductB(ABC):
    @abstractmethod
    def useful_function_b(self):
        pass

class ConcreteProductA1(AbstractProductA):
    def useful_function_a(self):
        return "A1"

class ConcreteProductB1(AbstractProductB):
    def useful_function_b(self):
        return "B1"

class AbstractFactory(ABC):
    @abstractmethod
    def create_product_a(self):
        pass

    @abstractmethod
    def create_product_b(self):
        pass

class ConcreteFactory1(AbstractFactory):
    def create_product_a(self):
        return ConcreteProductA1()

    def create_product_b(self):
        return ConcreteProductB1()

factory = ConcreteFactory1()
product_a = factory.create_product_a()
product_b = factory.create_product_b()
print(product_a.useful_function_a())  # Output: A1
print(product_b.useful_function_b())  # Output: B1
Explain the differences between Factory Method and… - sobes.tech