Abstract Factory Pattern
In part two I introduced factory pattern, here I introduce abstract factory and most important the differences between the two patterns. Abstract factory adds one abstract level in factory patter. To put it simply, you can view abstract factory as a factory of factories.
Abstract factory is a creational design pattern, it adds another abstraction level to factory method by encapsulating a group of factory methods. Abstract factory is used to create a family of related objects – factories that create related object – without specifying their concrete implementation. One more definition, abstract factory is a super factory that creates smaller factories that create related objects.
Let me take my previous example of transportation factory and add one level of abstraction. Lets say we need to group transportation into groups. Cheap transportation, middle cost transportation, expensive transportation and let us have a company for each group that provides a certain type of transportation, CheapTrans, SeemlessTransportation, BestTrans. Our super factory will create other factories (these 3 companies) that will create transportation objects. The transportation objects are the related families of objects, the companies are the factories, the factory that will create these factories is the abstract factory.
Examples from Java
All of these methods create concrete factories, these factories create concrete related objects.
Where to use
The pattern can be used where we need to create sets of objects that share a
common theme and where the client only needs to know how to handle the
abstract equivalence of these objects, i.e. the implementation is not
important for the client. It is often employed when there
is a need to use different sets of objects and where the objects could be
added or changed some time during the lifetime of an application.
Use of this pattern makes it possible to interchange concrete classes without
changing the code that uses them, even at runtime.
As with similar design patterns, one of the main drawbacks is the possibility
of unnecessary complexity and extra work in the initial writing of the code.
GoF Design Patterns – with examples using Java and UML2