What is the Factory pattern, and when would you use it?
MediumConceptDesign Patterns
Answer
The Factory pattern moves object creation into a dedicated method or class, so client code asks for an object by type or input and receives an implementation behind a common interface. Use it when the exact class to instantiate depends on configuration or run-time data.
- Simple factory: a static method such as
NotificationFactory.create("sms")returns anSmsNotificationor anEmailNotification. - Factory Method: a base class declares a creation method, and subclasses override it to decide which product to create.
- Abstract Factory: creates families of related objects, such as matching buttons and menus for a light or dark theme.
- Benefits: callers depend only on the interface, and adding a new type changes the factory rather than every caller.
More in Design Patterns
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What is the Singleton pattern, and what are its drawbacks? | Concept | Easy | Read the answer to What is the Singleton pattern, and what are its drawbacks? | |||
| 2 | What is the Factory pattern, and when would you use it? | Concept | Medium | Read the answer to What is the Factory pattern, and when would you use it? | |||
| 3 | How does the Observer pattern work, and where is it used? | Concept | Medium | Read the answer to How does the Observer pattern work, and where is it used? | |||
| 4 | What is the Strategy pattern, and how does it differ from the State pattern? | Concept | Medium | Read the answer to What is the Strategy pattern, and how does it differ from the State pattern? |