Factory Pattern

  • aka “Simple Factory” or “Static Factory Method”
  • Java Examples:
    • Calendar
    • NumberFormat
  • Note: Use of abstract class vs interface is really not that important
  • There is difference b/w of static factory and GoF factory pattern (confusing)
  • Classes
public interface Shape {
   void draw();
}
 
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
  • Factory
public class ShapeFactory {
   public Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }
      if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
      
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
   }
}
  • Driver
public class Demo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape circle = shapeFactory.getShape("CIRCLE");
        Shape rectangle = shapeFactory.getShape("RECTANGLE");
    }
}

UML

  • I think ideally the arrow for implements should be empty arrow but I have no idea whether a filled arrow is same or not Factory_Pattern_UML