Is the Composite Pattern SOLID?

前端 未结 4 1430
天涯浪人
天涯浪人 2021-01-02 04:19

A Leaf in the Composite Pattern implements the Component interface, including Add, Remove, and GetChild methods that a Leaf is never g

4条回答
  •  感情败类
    2021-01-02 04:48

    The GoF book specifically addresses this issue on page 167.

    Although the Composite class implements the Add and Remove operations for managing children, an important issue in the Composite pattern is which classes declare these operations... Should we declare these operations in the Component and make them meaningful for Leaf classes, or should we declare and define them only in Composite?

    The decision involves a trade-off between safety and transparency:

    • Defining the child management interface at the root of the class hierarchy gives you transparency, because you can treat all components uniformly. It costs you safety, however, because clients may try to do meaningless things like add and remove objects from leaves.
    • Defining child management in the Composite class gives you safety, because any attempt to add or remove objects from leaves will be caught at compile-time in a statically typed language like C++. But you lose transparency, because leaves and composites have different interfaces.

    We have emphasized transparency over safety in this pattern.

    The last sentence is an admission that the pattern violates type-safety principles. In terms of SOLID, this would primarily be LSP, but possibly ISP as well. Note that "declaring methods which a subclass doesn't use" is an oversimplification of ISP. The real danger of those unused methods is that they will require additional dependencies which the subclass didn't need, increasing coupling between modules.

提交回复
热议问题