DevPrep

All topics › Design patterns

Factory Method

Middle PRO

Essence

Factory Method (the "virtual constructor") is a creational pattern: a base type declares a method that creates a product, and which product to create is decided by a subtype or a concrete implementation. Client code works with the abstract product (any Exporter) and is not tied to concrete classes. It is Open/Closed in practice: a new product is added as a new implementation while old code stays untouched.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store