Friday, March 4, 2016

FACTORY DESIGN PATTERN EXAMPLE

/*
Creational Patterns - Factory Pattern
Factory of what? Of classes.
In simple words, 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.
*/
class Person {

public String name;
private String gender;

public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}

public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}

}


class Male extends Person {
  public Male(String fullName) {
setName(fullName);
setGender("Male");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Mr. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}
}


class Female extends Person {
  public Female(String fullName) {
setName(fullName);
setGender("Female");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Ms. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}

}

class DPFactory{
  public static void main(String args[]) {

DPFactory factory = new DPFactory();
Person  person = factory.getPerson(args[0], args[1]);
System.out.println(person);

}
public Person getPerson(String name, String gender) {
if (gender.equals("M")){
return new Male(name);
}else if(gender.equals("F")){
return new Female(name);
}else{
return null;
}
}
}

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...