Monday, 18 April 2016

What is a 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.

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. and if the sex is Female (F), it displays message saying Hello Ms.
public class Person {
    public String name;
    private String gender;   // gender : M or F
    public String getName() { return name;  }
    public String getGender() {  return gender;  }
}

Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.
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);
   }
}

Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.

public class SalutationFactory {
   public static void main(String args[]) {
      SalutationFactory factory = new SalutationFactory();
      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;
   }
}


When to use a Factory Pattern ?

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.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.