Welcome!

Java Authors: Liz McMillan, Pat Romanski, Roger Strukhoff, Jason Thompson, Elizabeth White

Related Topics: Java, SOA & WOA, Open Source, Eclipse, AJAX & REA

Java: Tutorial

Factory Design Pattern - An Effective Approach

How to create a better and most effective way of designing a Factory Design Pattern

As you know the Factory Method Pattern or popularly known as the Factory Design Pattern is one the design patterns under the category of "Creational Design Pattern". The basic principle behind the pattern is that at runtime we get an object of similar type based on the parameter we pass. There are many articles on this pattern and developers implement in various ways to achieve it. In this article I will show you how to create a better and most effective way of designing factory design pattern.

Technicalities
As I have told you we will get a similar type object at run-time in the case of a factory design so that the underlying implementation of an object will be behind the screen. Let us consider a simple approach. Let's consider a Person object that can be either Male or Female. At runtime we should only consider the behavior of the person but not the gender. As the traditional approach we create a Person interface and we create two implementation classes like MalePerson and FemalePerson. Based upon the runtime gender data, we pass to a Factory method of a Factory class where we decide whether the gender type is Male or Female and accordingly we create the instance of the particular class and return the reference type object. This approach sounds good and we adopt it in many of our developmental activities. Can we ensure that it is the effective approach in the case of fine-grained multi-threaded applications. What about the performance? Is there any other approach? Yes we do.

Let's consider another real time example. Think about a situation in an organization where an employee can be CEO, CTO, CFO, Developer, Test Engineer, HR, Personnel, Security etc. If you want to know the role of an employee based upon the organization, what will you do ? How will you create a better factory design so that we can easily find the role and there should not be performance penalty ? Will you adopt the same traditional approach by providing multiple if clauses ? You can make an argument that , we should use switch condition. Fine... Let us see traditional approach and let us measure the time.

More Stories By Debadatta Mishra

Debadatta Mishra is a senior Java developer with five years of experience in the field of Java and related technologies. He has written many articles on Java-related technologies on the Internet.