Cricinfo Live Scores

Sunday, February 3, 2008

Design Pattern (GOF): Creational Pattern : Factory Method

Definition

Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.

Example

To illustrate how to use factory design pattern with class level implementation, here is a real world example. A company has a website to display testing result from a plain text file. Recently, the company purchased a new machine which produces a binary data file, another new machine on the way, it is possible that one will produce different data file. How to write a system to deal with such change. The website just needs data to display. Your job is to provide the specified data format for the website.

Here comes a solution. Use an interface type to converge the different data file format. The following is a skeleton of implementation.

//Let's say the interface is Display
interface Display {

//load a file
public void load(String fileName);

//parse the file and make a consistent data type
public void formatConsistency();

}

//deal with plain text file
class CSVFile implements Display{

public void load(String textfile) {
System.out.println("load from a txt file");
}
public void formatConsistency() {
System.out.println("txt file format changed");
}
}

//deal with XML format file
class XMLFile implements Display {

public void load(String xmlfile) {
System.out.println("load from an xml file");
}
public void formatConsistency() {
System.out.println("xml file format changed");
}
}

//deal with binary format file
class DBFile implements Display {

public void load(String dbfile) {
System.out.println("load from a db file");
}
public void formatConsistency() {
System.out.println("db file format changed");
}
}

//Test the functionality
class TestFactory {

public static void main(String[] args) {
Display display = null;

//use a command line data as a trigger
if (args[0].equals("1"))
display = new CSVFile();
else if (args[0].equals("2"))
display = new XMLFile();
else if (args[0].equals("3"))
display = new DBFile();
else
System.exit(1);

//converging code follows
display.load("");
display.formatConsistency();
}
}
//after compilation and run it

C:\>java TestFactory 1
load from a txt file
txt file format changed

C:\>java TestFactory 2
load from an xml file
xml file format changed

C:\>java TestFactory 3
load from a db file
db file format changed

In the future, the company may add more data file with different format, a programmer just adds a new class in accordingly. Such design saves a lot of code and is easy to maintain.

Author:
-----------------------
Kazi Masudul Alam
Software Engineer