Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Factory Method Pattern

1. Introduction

The Factory Method Pattern is a creational design pattern that defines an interface for creating an object, but allows subclasses to alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into your code.

2. Definition

The Factory Method Pattern provides a way to delegate the instantiation of an object to subclasses. This means that the client code does not need to know the specific class of the object that will be created. Instead, it relies on the factory method to handle the object creation.

3. Structure

UML Diagram


            class Factory {
                +createProduct(): Product
            }

            class ConcreteFactoryA {
                +createProduct(): ConcreteProductA
            }

            class ConcreteFactoryB {
                +createProduct(): ConcreteProductB
            }

            class Product {}
            class ConcreteProductA extends Product {}
            class ConcreteProductB extends Product {}
            

4. Implementation

Here is a simple implementation of the Factory Method Pattern in Python:


class Product:
    def operation(self):
        raise NotImplementedError("You should implement this method.")

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

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

class Creator:
    def factory_method(self):
        raise NotImplementedError("You should implement this method.")

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

class ConcreteCreatorB(Creator):
    def factory_method(self):
        return ConcreteProductB()

# Client code
def client_code(creator: Creator):
    product = creator.factory_method()
    print(product.operation())

if __name__ == "__main__":
    client_code(ConcreteCreatorA())  # Output: Result of ConcreteProductA
    client_code(ConcreteCreatorB())  # Output: Result of ConcreteProductB
            

5. Best Practices

  • Use the Factory Method Pattern when you have a common interface for multiple classes.
  • Isolate the instantiation of classes to enable easier testing and maintenance.
  • Keep the client code unaware of the class names by delegating the instantiation to factory methods.

6. FAQ

What is the main benefit of using the Factory Method Pattern?

The main benefit is to promote loose coupling in your code by hiding the instantiation logic behind a factory method.

When should I use the Factory Method Pattern?

You should use it when your code needs to create objects without specifying the exact class of the object that will be created.

Can the Factory Method Pattern be used in any programming language?

Yes, the Factory Method Pattern is a design pattern that can be implemented in any object-oriented programming language.