Factory Pattern
Problem
Who should be responsible for creating objects when there are special considerations, such as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so forth?
Solution
Create a Pure Fabrication object called a Factory that handles the creation.
Shape.java
public interface Shape {
void draw();
}
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("rectangle draw");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("square draw");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("circle draw");
}
}
ShapeFactory.java
public class ShapeFactory {
public Shape getShape(String shapeType){
if(shapeType == null) {
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
Original example is from tutorialspoint
Think
Think cohesion and coupling
Think future reuse and modification
Last updated
Was this helpful?