What is Factory pattern? Explain with example.
What is Factory pattern? Explain with example.
Factory pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the class of the object that will be created. The created object is returned by the factory method in form of an interface/abstract class and all classes that can be created must implement this interface or extend the abstract class. Factory pattern creates objects without exposing the instantiation logic. The client invoking the factory method provides an input which is used to decide which actual class to instantiate. This pattern is widely used in frameworks like Struts, JSF and Spring.
Let us understand this concept through an example. In the example below the client is the Factory class, the factory method is createShape, input used to decide the actual shape is shapeEnum, Square and Rectangle are the two concrete implementations of the abstract class Shape which is returned to the client.
// ShapeType is an enum to hold the// types of shapespublic enum ShapeType {
SQUARE, RECTANGLE; }
|
// Shape is an abstract super class for all      // shapespublic abstract class Shape {private ShapeType shape;
public Shape(ShapeType shape) { this.shape = shape; } public abstract void display(); }
|
// Square, Rectangle are concrete                   // implementations of Shape for a type.public class Square extends Shape{public Square() {
super(ShapeType.SQUARE); } @Override public void display() { System.out.println(“Square shape….”); } }
|
// ShapeFactory.java is our main class implemented using factory pattern.// It instantiates a shape based on its type.public class ShapeFactory {
public static Shape createShape(ShapeType shapeEnum) { Shape shape = null; switch(shapeEnum){ case SQUARE: shape = new Square(); break; case RECTANGLE: shape = new Rectangle(); break; } return shape; } }
|
// When you test this, will get the appropriate output….
public class Factory {
public static void main(String arg[]) {
Shape shape = ShapeFactory.createShape(ShapeType.SQUARE);
shape.display();
shape = ShapeFactory.createShape(ShapeType.RECTANGLE);
shape.display();
}
}
Output:
Square shape….
Rectangle shape….