Thursday 30 November 2017

Abstract Factory Design Pattern


Motivation
Modularization is a big issue in today's programming. Programmers all over the world are trying to avoid the idea of adding code to existing classes in order to make them support encapsulating more general information. Take the case of a information manager which manages phone number. Phone numbers have a particular rule on which they get generated depending on areas and countries. If at some point the application should be changed in order to support adding numbers form a new country, the code of the application would have to be changed and it would become more and more complicated.
In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a framework is defined, which produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory which creates other factories (Factory of factories).

Intent
Abstract Factory offers the interface for creating a family of related objects, without explicitly specifying their classes.

Where to use
Abstract Factory should be used when:
A system should be configured with one of multiple families of products
A system should be independent of how its products are created, composed and represented
Products from the same family should be used all together, products from different families ahould not be used together and this constraint must be ensured.
Only the product interfaces are revealed, the implementations remains hidden to the clients.

Common Usage
Examples of abstract factories:
java.awt.Toolkit - the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of Toolkit are used to bind the various components to particular native toolkit implementations(Java AWT).
javax.swing.LookAndFeel - an abstract swing factory to swithct between several look and feel for the components displayed(Java Swing).
java.sql.Connection - an abstract factory which create Statements, PreparedStatements, CallableStatements,... for each database flavor.
Example: Gui Look & Feel in Java

Applicability
Use the Abstract Factory pattern when
1. a system should be independent of how its products are created, composed, and represented.
2. a system should be configured with one of multiple families of products.
3. a family of related product objects is designed to be used together, and you need to enforce this constraint.
4. you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Benefit(s)
1. It isolates concrete classes.
2. It makes exchanging product families easy.
3. It promotes consistency among products.

Disadvantage(s)
1. Supporting new kinds of products is difficult.

Happy Learning.

1 comment: