My understanding of Factory Pattern
Going by definition Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.
In simple terms we can say that factory pattern is a good choice when we need to create object depending on some parameter at runtime.
Let’s say if we have a super class and sub-classes, and based on data provided (any parameter), we have to return the object of one of the sub-classes, then factory pattern is the ideal choice.
Lets take a simple example to understand its working..
Suppose we have an application which stores Customer details like name and sex etc. Depending on sex the application will create either a male or a female object and accordingly print a hello message.
public class Customer {
public String name;
//gender : M or F
private String gender;
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}
Customer class is having methods for name and gender. And the sub classes will print hello message as shown below.
public class Male extends Customer {
public Male(String name) {
System.out.println("Hello Mr. "+name);
}
}
public class Female extends Customer {
public Female(String name) {
System.out.println("Hello Ms. "+name);
}
}
Now create a client, called CustomerFactory which will return Male or Female object depending on the data provided
public class CustomerFactory {
public static void main(String args[]) {
CustomerFactory factory = new CustomerFactory();
factory.getCustomer(args[0], args[1]);
}
public Customer getCustomer(String name, String gender) {
if (gender.equals("M"))
return new Male(name);
else if(gender.equals("F"))
return new Female(name);
else
return null;
}
}
On compiling and running this client program..
Java CustomerFactory Sarah F
The output is: “Hello Ms. Sarah”.
Now let’s summarize when to use Factory Pattern
· When a class does not know which class of objects it must create.
· When we want to encapsulate the process of creating the objects.
· When we have to create an object of any one of sub-classes depending on the data provided.
So now its time to create your own factories as you wish J
Labels: design pattern, Java

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home