OCP quy định một module phải mở để mở rộng nhưng đóng để sửa đổi — thêm tính năng mới mà không cần chỉnh sửa code hiện có.
Ví dụ TypeScript:
typescript
interface DiscountStrategy {
apply(price: number): number
}
class SeasonalDiscount implements DiscountStrategy {
apply(price: number) { return price * 0.8 }
}
class LoyaltyDiscount implements DiscountStrategy {
apply(price: number) { return price * 0.9 }
}
// Thêm loại discount mới: chỉ cần tạo class mới, không sửa calculatePrice()OCP thường được triển khai qua Strategy pattern, Template Method hoặc polymorphism.
Vi phạm OCP thường biểu hiện ở switch/case hay if/else if dài dần theo thời gian.