OOP Design Patterns — Factory Pattern

Dinesha Karunathilake
2 min readNov 28, 2020

Encapsulate what changes: Object instantiation is something that is more prone to change. When a new type of object need to be added to extend functionality it will change. Encapsulating these changing parts is what we are focused on here.

All factory patterns encapsulate the object creation

Also, both the below patterns makes sure that we depend on abstractions, not implementations

Factory Method Pattern

The factory method pattern encapsulates object creation by letting subclasses decide what objects to create.

Definition: Factory Method Pattern defines an interface for creating an object but lets the subclass decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory method pattern UML
  • All products must implement the same interface so that the clients can refer to the interface not the concrete class
  • Creator — A class that contains implementations of all methods to manipulate the object other than the Factory method
  • abstract factoryMethod() is what all subclasses should implement
  • ConcreteCreator implements the factoryMethod() which produces products
  • ConcreteCreator is responsible for creating one or more concrete products. Only it has the knowledge.

This also helps to program to an interface not an implementation

Abstract Factory Pattern

Definition: Abstract factory pattern provides an interface for families of related or dependent objects without specifying their concrete classes.

We can look at the abstract factory pattern as a pattern comprising of many factory methods, ie the Abstract Factory contains multiple factory methods. Each method in that interface is responsible for creating a concrete product, as we implement a subclass of the Abstract Factory to supply those implementations.

Both these patterns help decouple applications from specific implementations: keeps clients decoupled from the concrete types, but in different ways. This can be a bit confusing.

  • Both encapsulate creation of objects: Factory method pattern uses inheritance while Abstract Factory uses object composition.
  • While Factory method creates one object, abstract factory creates a family of related objects

https://github.com/DineshaKarunathilake/DesignPatterns/tree/master/factory

--

--