Software Design Patterns
Creational Patterns
Structural Patterns
Behavioral Patterns
Factory Method Design Pattern
This is a creational pattern.
Centralize creation of an object of a specific type choosing one
of several implementations.
Factory Method Design Pattern
Suppose, we have a super class named “Person”. Two
other classes, “Student” and “Teacher”, have been
created by extending the “Person” class. We will create
another class where a particular method will take the
responsibility of creating any one of the two sub-
classes.
Factory Method Design Pattern (Example)
class Person
{
String name;
int height, weight;
public void printDetails ()
{
System.out.println ("Name: "+name+", height:
"+height+", weight: "+weight);
}
}
Factory Method Design Pattern (Example)
class Student extends Person
{
int studentid;
public void printDetails ()
{
System.out.println ("Name: "+name+", height:
"+height+", weight: "+weight+", student id: "+studentid);
}
}
Factory Method Design Pattern (Example)
class Teacher extends Person
{
String subject;
public void printDetails ()
{
System.out.println ("Name: "+name+", height: "+height+", weight: "+weight+",
course: "+showSubject ());
}
public String showSubject ()
{
if (subject == null) { return "not assigned yet"; }
return subject;
}
}
Factory Method Design Pattern (Example)
class PersonFactory
{
public Person makePerson (int ptype, String pname, int pheight, int pweight)
{
if (ptype == 1) //this is for student
{
Student s = new Student ();
s.name = pname;
s.height = pheight;
s.weight = pweight;
return s;
}
else
{
Teacher t = new Teacher ();
t.name = pname;
t.height = pheight;
t.weight = pweight;
return t;
}
}
}
Factory Method Design Pattern (Example)
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
PersonFactory factory = new PersonFactory ();
Person p1 = factory.makePerson(1, "Karim", 0, 0);
Person p2 = factory.makePerson(2, "Barek", 0, 0);
p1.printDetails();
p2.printDetails();
}
}
Factory Method Design Pattern
How can we apply this pattern for making a calculator
that can perform addition and subtraction?
Use Abstract Factory Design Pattern to implement a calculator that
performs two operations: addition and subtraction. The objects of the
addition and subtraction classes should have a method to return the
result of operation (add/subtract).