Thursday, February 12, 2009

Factory Design Pattern

Factory Design Pattern:
Factory design pattern is all about having "factory of objects". Here we declare a class (factory) whose job is to instantiate appropriate object out of various objects in parallel hierarchy based on the input given by calling program.

Implementation:
Consider a base class Namer. Suppose it has two subclasses LastFirst and FirstFirst. Then we have a factory class NameFactory. The factory class instantiates either LastFirst or FirstFirst depending upon the String name parameter received from the client.

public class Namer
{
private String firstName;
private String lastName;
public String getFirst()
{
return firstName;
}
public String getLast()
{
return lastName;
}
}

public class FirstFirst extends Namer
{
pubic FirstFirst(String s)
{
int i = s.lastIndexOf(" ");
if(i > 0)
{
firstName = s.substring(0,i).trim();
lastName = s.substring(i+1).trin();
}
else
{
firsName = "";
lastName = s;
}
}
}

public class SecondFirst extends Namer
{
public SecondFirst(String s)
{
int i = s.indexOf(",");
lastName = s.substring(0,i).trim();
firstName = s.substring(i+1).trim();
}
}

class NameFactory
{
public static Name getNamer(String name)
{
int i = name.indexOf(",");
if(i > 0)
{
return new LastFirst(name);
}
else
{
return new FirstFirst(name);
}
}

class Client
{
NameFactory.getNamer(shakil,shahnawaz).getFirst();
NameFactory.getNamer(shakil,shahnawaz).getLast();
}


As we can see in the above example, client is printing the first and last name without knowing which class is being called by the factory class.

Examples of Factory Design Pattern:
1) COM Application
The factory role is poayed by IClassFactory
2) Standard Template Library (STL)
3) EJB:
Creation of entity beans
4) CORBA
CosNaming.Factory plays the role of factory.

No comments:

Post a Comment