Design Patterns · java

Factory Design Pattern

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.

Example: Let’s 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>.

a getPerson which will return the welcome message depending on the data provided.

public class Person {
// name string
public String name;
// gender : M or F
private String gender;
public String getName() {
        return name;
public String getGender() {
return gender;
public static Person getPerson(String name, String gender) {
if (gender.equals("M"))
  return new Male(name);
else if (gender.equals("F"))
  return new Female(name);
  return null;
public class Male extends Person {
public Male(String fullName) {
System.out.println("Hello Mr. " + fullName);
public class Female extends Person {
public Female(String fullNname) {
System.out.println("Hello Ms. " + fullNname);
public static void main(String args[]) {

Person.getPerson("ali", "M");
Person.getPerson("sara", "F");


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s