Factory Method định nghĩa interface để tạo object nhưng để subclass quyết định class nào sẽ được instantiate — class cha không hard-code class con cụ thể.
Ví dụ TypeScript:
typescript
abstract class Notification {
abstract createSender(): Sender
send(msg: string) {
this.createSender().send(msg)
}
}
class EmailNotification extends Notification {
createSender() { return new EmailSender() }
}Khác với Simple Factory (không phải GoF pattern): Simple Factory chỉ là một method/class có logic if/else tạo object — dễ hiểu nhưng vi phạm OCP vì phải sửa khi thêm type mới.
- Factory Method tuân thủ OCP vì thêm type mới chỉ cần tạo subclass mới.
- Dùng Factory Method khi: framework cần cho phép extension mà không biết trước loại object sẽ tạo; khi muốn user override cách tạo object.
- Không dùng khi: hierarchy đơn giản, Simple Factory đủ dùng.