Simple Factory Pattern in Java: Explanation & Practice

Create objects using factory method

Problem summary

Create a ShapeFactory that creates different shapes based on input type.

Starter code

// Shape interface with draw()
// ShapeFactory with createShape(String type)
// Returns Circle, Square, or Triangle

public class Main {
    public static void main(String[] args) {
        // Use factory to create and draw shapes
    }
}

Expected output and test cases

  • Create circle
    Drawing circle
  • Create square
    Drawing square
  • Invalid type
    Unknown shape

Hints

  1. Factory method returns interface type
  2. Switch/if on input string
  3. Return appropriate implementation

Related Inheritance exercises

Practice all Inheritance exercises · Run this idea in the Java compiler