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
- Factory method returns interface type
- Switch/if on input string
- Return appropriate implementation
Related Inheritance exercises
- Practice Comparable Implementation in Java
- Practice Template Method Pattern in Java
- Practice Simple Decorator in Java
Practice all Inheritance exercises · Run this idea in the Java compiler