Beginner LevelSoftware Engineering Principles
What is the Factory Method Pattern and when should you use it?
❓ Interview Prompt: Explain the Factory Method Creational Pattern, abstracting object instantiation, and decoupling client code from concrete classes.
The Factory Method Pattern is a creational design pattern that defines an interface or abstract method for creating objects, allowing subclasses or factory functions to decide which concrete class to instantiate:
Benefits:
•
Decoupling: Client code depends strictly on abstract product interfaces, not concrete implementations ('new ConcreteClass()').
•
Open/Closed Principle: Adding a new product type requires adding a new Factory implementation without modifying existing client code.
Code Implementation Example
typescript
interface Notification { send(message: string): void; }
class EmailNotification implements Notification { send(msg: string) { console.log('Email:', msg); } }
class SMSNotification implements Notification { send(msg: string) { console.log('SMS:', msg); } }
// Factory Method
class NotificationFactory {
static create(type: 'email' | 'sms'): Notification {
if (type === 'email') return new EmailNotification();
if (type === 'sms') return new SMSNotification();
throw new Error('Unknown notification type');
}
}💡Creating dynamic objects using the Factory Method pattern.
🎯 Interview Key Takeaway
Use the Factory Method pattern to decouple object creation logic from client code.
#Design Patterns#Factory Method#Creational#Beginner
Back to all Software Engineering Principles Questions→