Monday, April 11, 2011

Design Pattern : Factory Pattern

Creational Patterns - Factory Pattern ( Methods to make and return components of one object various ways):


When to use ?

If we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.

The Factory patterns can be used in following cases:

1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.


Example:

Below Example have Person as a Super class and Male and Female extends Person.Finally in main program we can create person object based on Male or Female.


/**
*
* @author R.Amirtharaj
*/
public class Person {

// Name of the Person
private String strName;
// Gender : M or F
private String strGender;

public String getStrGender() {
return strGender;
}

public void setStrGender(String strGender) {
this.strGender = strGender;
}

public String getStrName() {
return strName;
}

public void setStrName(String strName) {
this.strName = strName;
}

}



/**
*
* @author R.Amirtharaj
*/
public class Male extends Person {

public Male(String strName) {
System.out.println("Hello Mr. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class FeMale extends Person {

public FeMale(String strName) {
System.out.println("Hello Ms. " + strName);
}
}

/**
*
* @author R.Amirtharaj
*/
public class Demo {

public static void main(String args[]) {
Demo factoryDemo = new Demo();
factoryDemo.getPerson(args[0], args[1]);
//factoryDemo.getPerson("Amir", "M");

}

public Person getPerson(String strName, String strGender) {
if (strGender.equals("M")) {
return new Male(strName);
} else if (strGender.equals("F")) {
return new FeMale(strName);
} else {
return null;
}
}
}

No comments:

Post a Comment