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
- Create Shape interface with draw()
- Implement Circle and Rectangle
- Factory uses switch/if to return correct type
Related OOP Basics exercises
- Practice Music Playlist Manager in Java
- Practice Singleton Pattern in Java
- Practice Builder Pattern in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler