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");


About lorddisk

WebCenter Content, WebCenter Portal, WebCenter Sites,Weblogic, Identity and Access Management (IAM),SSO,OAM,OIM,OAAM,OUD, OPAM,OID, OVD ,Oracle API Gateway ,OBIEE,OEDQ, Oracle ADF, Oracle SOA,J2EE, CackePHP ,PHP,J2SE,J2EE,Spring,Hibernate,JQuery,CSS,Java Script ,Joomla,Drupal,Worpress
This entry was posted in Design Patterns, java and tagged . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s