Decorator pattern versus sub classing

后端 未结 6 924
陌清茗
陌清茗 2020-12-07 16:17

I can solve the problem of adding functionality by adding sub classing then why should I use decorator pattern what\'s the real advantage of decorator pattern ?

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 17:02

    from Decorator pattern at wikipedia

    The decorator pattern can be used to make it possible to extend (decorate) the functionality of a certain object at runtime.

    The whole point of decorator pattern is to dynamically add additional behaviour/functionality, which is of course not possible at design time.

    from the same article:

    The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.

提交回复
热议问题