Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 min

Factory Method: The Virtual Constructor

Delegate object creation to subclasses — decouple the client from the concrete classes it instantiates.

Why this matters

When you scatter new CSVParser() and new JSONParser() across your codebase, you bind the client tightly to concrete class names. Every time a new format arrives, you hunt down every if type == "csv" block. The Factory Method pattern defines an interface for creation but lets subclasses — or a factory function — decide which concrete class to instantiate. Adding a new type touches zero existing code.

When to use it — and when not to

Use Factory Method when a class cannot anticipate the type of objects it needs to create, or when you want subclasses to control creation. Avoid it when you only ever have one concrete implementation — it adds indirection for no gain.

💡Key takeaway

Replace scattered if type == X: create X blocks with a single factory — adding new types then requires writing new code, never modifying old code.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

Hint: If you find yourself writing 'if type == X: create X' in multiple places, you need a Factory Method.

✗ Your version

Factory Method: The Virtual Constructor — CleanKata — CleanKata