Thursday, August 25, 2011

Difference between Factory and Abstract Factory Pattern

Difference between Factory and Abstract Factory Pattern:-









Factory
Abstract Factory

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.


Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.


The client expects an implementation of an interface or abstract class, but doesn't know exactly what concrete class the factory will return.


Here, there is one more level of abstraction. The client does not even know what factory it's going to use. First, it gets a Factory and then it calls a Factory method. The following example will explain this.

The Factory Method creates objects through inheritance.


Abstract Factory creates objects through composition.


Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible of creating products that belong to one family


While Abstract Factory pattern deals with multiple families of products.


Abstract Factory vs. Factory Method The methods of an Abstract Factory are implemented as Factory Methods.


Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories.




Real Life Example:-

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.


Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.



1 comments:

Anonymous said...

Thank you Manish for telling the difference between factory and abstract factory pattern.It is very understandable.