Factory Pattern in Java: Explanation & Practice

Implement the factory design pattern

Problem summary

Create a ShapeFactory that creates different shapes (Circle, Rectangle) based on a string input.

Starter code

interface Shape {
    void draw();
}

// Implement Circle and Rectangle classes
// Implement ShapeFactory

public class Main {
    public static void main(String[] args) {
        Shape circle = ShapeFactory.createShape("circle");
        Shape rect = ShapeFactory.createShape("rectangle");
        
        circle.draw();
        rect.draw();
    }
}

Expected output and test cases

  • Factory creates correct shapes
    Drawing Circle
    Drawing Rectangle

Hints

  1. Create Shape interface with draw()
  2. Implement Circle and Rectangle
  3. Factory uses switch/if to return correct type

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler