Factory
Factory Pattern an interface is responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the data passed.
We are developing an enterprise application. You are responsible for authentication module. But you are not sure how you are going to do authentication. You can have authentication against LDAP, database or any other centralized directory. So you first define an interface for authentication with single method authorize() This method returns true if user is successfully authenticated or false if not authenticated.
The Factory Method Design Pattern in Java
Parent Class:
=============
public interface Shape {
public String draw();
}
Derived Class 1
===============
public class Circle implements Shape {
@Override
public String draw() {
return “Circle draw ...“;
}
}
Derived Class 2:
===============
public class Triangle implements Shape {
@Override
public String draw() {
return “Triangle draw …”;
}
}
Derived Class 3:
===============
public class Rectangle implements Shape {
@Override
public String draw() {
return “Rectangle draw …”;
}
}
Factory Class:
==============
public class ShapeFactory {
public Shape getShape(String shapeType) {
Shape shape = null;
if (“circle”.equals(shapeType))
shape = new Circle();
else if (“triangle “.equals(shapeType))
shape = new Triangle ();
else if (“rectangle “.equals(shapeType))
shape = new Rectangle ();
return shape;
}
We are developing an enterprise application. You are responsible for authentication module. But you are not sure how you are going to do authentication. You can have authentication against LDAP, database or any other centralized directory. So you first define an interface for authentication with single method authorize() This method returns true if user is successfully authenticated or false if not authenticated.
The Factory Method Design Pattern in Java
Parent Class:
=============
public interface Shape {
public String draw();
}
Derived Class 1
===============
public class Circle implements Shape {
@Override
public String draw() {
return “Circle draw ...“;
}
}
Derived Class 2:
===============
public class Triangle implements Shape {
@Override
public String draw() {
return “Triangle draw …”;
}
}
Derived Class 3:
===============
public class Rectangle implements Shape {
@Override
public String draw() {
return “Rectangle draw …”;
}
}
Factory Class:
==============
public class ShapeFactory {
public Shape getShape(String shapeType) {
Shape shape = null;
if (“circle”.equals(shapeType))
shape = new Circle();
else if (“triangle “.equals(shapeType))
shape = new Triangle ();
else if (“rectangle “.equals(shapeType))
shape = new Rectangle ();
return shape;
}