The Factory Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
For instance, let's look at this diagram
- The relation between product and concrete product is that all products must implement the same product interface
- The "ConcreteCreator" is responsible for creating one or more concrete products
- The abstract "FactoryMethod()" is what all creator subclasses must implement
Q) So, what is the diagram trying to tell us here?
- It is telling us to depend upon abstractions, not concrete classes (Dependency Inversion Principle). Remember? the Factory Pattern, once again, defines an interface for creating an object and its subclasses decide which class to instantiate. So, the D.I.P and Factory Pattern go hand-in-hand.
- A few key points of the Dependency Inversion Principle to remember:
- No variables should hold a reference to a concrete class
- No class should derive from a concrete class
- No method should override an implemented method of any of its base classes
The Abstract Factory Pattern
It is a version of the Factory Pattern, but with more abstract. This pattern provides an interface (abstract type) for creating families of related or dependent objects without specifying their concrete classes.
Subclasses of this type define how those products are produced. To use the factory, instantiate one and pass it into some code written against the abstract type. Then, group together a set of related products (can be a big interface) and the interface has to change if new products are added.
It can be little confusing to tell apart what differentiates these two patterns from one another at first. Just know these two things:
- The Factory Method Pattern defers instantiation to its subclasses through inheritance; delegate object creation to subclasses
- The Abstract Factory Pattern provides an abstract type for creating a FAMILY of products through object composition.
- If you are not familiar with object composition, check out my positing on The Strategy Pattern