Build a Shape Factory
Advanced · Write the code · from Python Design Patterns: Factory, Strategy, Observer, and More
From the lesson: Python Design Patterns: Factory, Strategy, Observer, and More
Design patterns are proven recipes for solving common software problems. Think of them like architectural blueprints -- you wouldn't redesign plumbing from scratch for every house. Patterns give your code a shared vocabulary so other developers instantly understand your intent.
Read the lessonCreate a factory function called create_shape that takes a string ('circle', 'square', or 'triangle') and returns an instance of the corresponding class. Each class should have an area() method:
Circle: area() returns 3.14 (simplified)Square: area() returns 4 (side=2, area=2*2)Triangle: area() returns 3.0 (base=3, height=2, area=0.5*3*2)Raise ValueError for unknown shapes. Print the area of a circle.
What Check runs
Your code runs first, then each of these lines. The output must match exactly.
| Runs | Expected output |
|---|---|
| print(create_shape('square').area()) | 3.14 4 |
| print(create_shape('triangle').area()) | 3.14 3.0 |
More Design Patterns exercises
- Strategy Pattern with FunctionsAdvanced
- Build an Event SystemAdvanced
- Predict Singleton BehaviorAdvanced
- Implement the Decorator PatternAdvanced
- Template Method PatternAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz