What is the difference between Factory and Abstract Factory Patterns


What is the difference between Factory and Abstract Factory Patterns?

✍: Guest


Note: - This is quiet a confusing architect question especially in design pattern section. Interviewer can take you for a nice ride. So get the difference in your heart.
First read the definition provided in the first question about both these patterns. The common thing they have is that they belong to creational patterns. In short they hide the complexity of creating objects.
The main difference between factory and Abstract factory is factory method uses inheritance to decide which object has to be instantiated while abstract factory uses delegation to decide instantiation of object. We can say Abstract factory uses factory method to complete the architecture. Abstract Factory is one level higher in abstraction over Factory.
The two class diagrams below will provide overview of what is the actual difference. First figure shows a sample implementation of Factory Patterns. In this figure there are two basic sections:-

ã The actual product section i.e. Class gProducth it inherits from an abstract class gAbstractProducth.
ã The creational aspect section i.e. gConcreteCreatorh class which inherits from class gCreatorh.
ã Now there are some rules the client will have to follow who will need the gProducth object. He will never refer directly to the actual gProducth object he will refer the gProducth object using gAbstractProducth.
ã Second client will never use gNewh keyword to create the gProducth object but will use the gCreatorh class which in turn will use the gConcreteCreatorh class to create the actual gProducth object.

So what are the benefits from this architecture? All creational and initializing aspects are now detached from the actual client. As your creational aspect is now been handled in “ConcreteCreator” and the client has reference to only “Creator”, so any implementation change in “CreateProduct” will not affect the client code. In short now your creational aspect of object is completely encapsulated from the client’s logic.
Now let’s look at the second class diagram which provides an overview of what actually “Abstract factory” pattern is. It creates objects for families of classes. In short it describes collection of factor methods from various different families. In short it groups related factory methods. Example in this the class “Creator” is implemented using the “Abstract” factory pattern. It now creates objects from multiple families rather one product.
Note :- Just stick up to this definition that Abstract factory classifies factory methods or groups logically related factory method together.

2007-10-24, 5302👍, 0💬