Monday, 2 January 2017

Difference between AbstractFactory and Factory design patterns

Factory Method is used to create one product only but Abstract Factory is about creating families of related or dependent products.

Factory Method pattern exposes a method to the client for creating the object whereas in case of Abstract Factory they expose a family of related objects which may consist of these Factory methods.

Factory Method pattern hides the construction of single object whereas Abstract factory method hides the construction of a family of related objects. Abstract factories are usually implemented using (a set of) factory methods.

AbstractFactory pattern uses composition to delegate responsibility of creating object to another class while Factory design pattern uses inheritance and relies on derived class or sub class to create object.

The idea behind the Factory Method pattern is that it allows for the case where a client doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job while AbstractFactory pattern is best utilized when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details.

Real Life Examples
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.

Abstract 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.

Factory Pattern:
1. Creates object through inheritance.
2. Produce only one product.
3. Implements code in the abstract creator that makes use of the concrete type that sub-class produces.

Abstract Factory Pattern:
1. Creates object through composition.
2. Produce families of products.
3. Concrete factories implements factory method to create product.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...