Trung BìnhDesign Patterns iconDesign Patterns

Decorator pattern là gì? Khác gì Inheritance? Ví dụ trong TypeScript?

Decorator đính kèm thêm behavior vào object tại runtime bằng cách bọc chúng trong decorator objects — thay thế cho inheritance khi cần linh hoạt.

Ví dụ TypeScript:

typescript
interface Coffee { cost(): number }

class SimpleCoffee implements Coffee {
  cost() { return 10 }
}

class MilkDecorator implements Coffee {
  constructor(private coffee: Coffee) {}
  cost() { return this.coffee.cost() + 2 }
}

class SugarDecorator implements Coffee {
  constructor(private coffee: Coffee) {}
  cost() { return this.coffee.cost() + 1 }
}

// Stack decorators:
const myCoffee = new SugarDecorator(new MilkDecorator(new SimpleCoffee()))
myCoffee.cost() // 13

Khác Inheritance: Decorator thêm behavior tại runtime và có thể stack nhiều lớp; inheritance static tại compile time và có thể gây explosion.

  • TypeScript @decorator syntax là Decorator pattern nhưng dành cho class/method metadata, không hẳn là GoF Decorator.
  • Dùng khi: cần thêm behavior mà không muốn sửa class gốc; khi cần combine nhiều behavior tùy chọn.
  • Không dùng khi: decorator stack quá sâu gây khó debug.

Xem toàn bộ Design Patterns cùng filter theo level & chủ đề con.

Mở danh sách Design Patterns