Decorator pattern versus sub classing

后端 未结 6 913
陌清茗
陌清茗 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:12

    Subclassing can lead to issues with the Liskov substitution principle. The decorator avoids this.

    Another advantage of the decorator is that you are writing (forced to write) to an interface. This makes things easier for testing. It is true that your object hierarchy can also be written to an interface and thus have some of the same advantages, however, I can test a single implementation of a decorator class in isolation. I cannot do the same with a subclass because I will always get the whole hierarchy back to the base class. I am unable to test the new code in isolation.

    Using the decorator pattern and following the single responsibility principle, I can create several decorators and stack them anyway I wish. I can configure that at runtime. In inheritance I either have to create every possible branch (a->b->c then a->c->b, thus duplicating code and exploding the number of tests), or I create 1 hierarchy then add another when needed, but this triggers a new test/release cycle.

    This is why you would want to use the decorator pattern instead of subclassing.

提交回复
热议问题