Factory pattern comes from creational design pattern category.main objective of this pattern is to instantiate an object and Factory pattern interface is responsible for creating objects but the sub-classes desides which class to instantiate.
Im going to start with a simple example.Suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. <Name> and if the sex is Female (F), it displays message saying Hello Ms <Name>.
First Im going to create a Person class..
we have 2 sub classes which will print welcome messages
Im going to create a WelcomeMessageFactory class which will return welcome messages according to the input data..
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;
}
}
This class accepts two arguments from the system at runtime and prints the names and sex..
after compiling run the program with
java Madura M
out put is
Mr. Madura
Im going to start with a simple example.Suppose an application asks for entering the name and sex of a person. If the sex is Male (M), it displays welcome message saying Hello Mr. <Name> and if the sex is Female (F), it displays message saying Hello Ms <Name>.
First Im going to create a Person class..
public class Person {
public String name;
public String gender;
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}
public String name;
public String gender;
public String getName() {
return name;
}
public String getGender() {
return gender;
}
}
we have 2 sub classes which will print welcome messages
public class Male extends Person {
public Male(String name) {
System.out.println("Mr. " + name);
}
}
public Male(String name) {
System.out.println("Mr. " + name);
}
}
public class Female extends Person {
public Female(String name) {
System.out.println("Ms." + name);
}
}
public Female(String name) {
System.out.println("Ms." + name);
}
}
Im going to create a WelcomeMessageFactory class which will return welcome messages according to the input data..
public class WelcomeMessageFactory{
private static void main(String args[]) {
WelcomeMessageFactory factory = new WelcomeMessageFactory();
factory.getPerson(args[0], args[1]);
}
private static void main(String args[]) {
WelcomeMessageFactory factory = new WelcomeMessageFactory();
factory.getPerson(args[0], args[1]);
}
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;
}
}
This class accepts two arguments from the system at runtime and prints the names and sex..
after compiling run the program with
java Madura M
out put is
Mr. Madura
Comments
Post a Comment