Is the Composite Pattern SOLID?

前端 未结 4 1441
天涯浪人
天涯浪人 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:31

    I would say that the Composite pattern as described in your link violates the Liskov substitution principle, one of the five SOLID principles.

    Component has methods that only make sense for a Composite e.g. Add(). Leaf inherits from Component so it will have an Add() method like any other Component. But Leafs don't have children, so the following method call cannot return a meaningful result:

    myLeaf.Add( someChild );

    That call would have to throw a MethodNotSupportedException, return null or indicate in some other way to the caller that adding a child to a Leaf does not make sense.

    Therefore you cannot treat a Leaf like any other Component because you'll get an exception if you try to. The Liskov substition principle states:

    Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.

    Components have the property that you can add children to them. But you cannot add children to a Leaf, even though Leaf is a subtype of Component, which violates the principle.

提交回复
热议问题