装饰器模式
字数: 0

基本概念

Decorator Pattern: Attach additional responsibilities to an object dynamically.
假设你正在开发一个提供通知功能的库, 其他程序可使用它向用户发送关于重要事件的通知。
notion image
  • 你可以尝试创建一个特殊子类来将多种通知方法组合在一起以解决该问题。 但这种方式会使得代码量迅速膨胀。
  • 另外一种方法是用聚合, 而不是继承。通过扩展“通知器类”, 在新的子类中加入额外的通知方法,而不需要修改其原始类。以便在运行时动态组合不同的通知方式,而不是创建大量的子类。
    • notion image
🔑
继承是静态的。你无法在运行时更改已有对象的行为,只能使用由不同子类创建的对象来替代当前的整个对象。
子类只能有一个父类。大部分编程语言不允许一个类同时继承多个类的行为。

实现代码

notion image

组件

Component

具体组件

Concrete Component

装饰器

Decorator
重写装饰基类的方法, 可以在调用父类方法之前或之后进行额外的行为。

具体装饰器

测试类

notion image

Q & A

Can you explain how composition is promoting a dynamic behavior that inheritance cannot?
  • Inheritance provides static behavior as the derived class inherits from the base class at compile-time.
  • Composition allows for dynamic behavior, offering more flexibility in extending objects and their capabilities.
What are the key advantages of using a decorator?
  • You do not need to predict all the supported functionalities at the initial design phase. You can develop incrementally.
  • The existing structure is untouched, so that you are not introducing bugs there. New functionalities can be easily added to an existing object.
    • notion image
What are the disadvantages associated with this pattern?
  • If you create too many decorators in the system, it will be hard to maintain and debug.
    • notion image

具体应用

Java I/O Streams

基本的 InputStream OutputStream 类提供了基础的功能,而装饰器类(如 BufferedInputStream, DataInputStream, PrintStream等)提供了额外的特性,例如缓冲、数据读写和格式化输出等。
 
2023 - 2026