2

In the gang of four book, the Composite pattern is defined with the diagram enter image description here

Why are methods only related to Composite part of the Component interface? If the methods (Add, Remove, Getchild) were part of Composite and not the general interface, Composites and Leaves would still both implement the Component interface and thus be used interchangably as is one of the purposes of the Composite pattern. By having both Leaf and Composite implement Component (that only requires Operation now), the client would still treat them the same like

Component anobject = new Leaf();
Component another = new Composite();
another.Operation();
anobject.Operation();
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • Possible duplicate of [Is the Composite Pattern SOLID?](https://stackoverflow.com/questions/1579520/is-the-composite-pattern-solid) – jaco0646 May 08 '19 at 21:41

2 Answers2

1

Because you treat composites and leafs the same. You program to interface, not to concrete objects.

In your example, you couldn't do:

Component l = new Leaf();
Component c = new Composite();

// now you can't do this because Composite doesn't know about add() method, only concrete subclass know in your variation.
composite.add(l); 
zar
  • 11,361
  • 14
  • 96
  • 178
  • Yea but wouldn't the client just create objects of `Composite` type and then directly on this object call `add` to add Component types. Then, from there on, you could store both the `Composite` object and `Leaf` or `Component` objects in a List of `Component`s as if `Leaf` and `Component` were the same? Then they would still be treated the same, right? –  May 09 '19 at 12:01
0

GOF define this kind of implementation because they want guarantee transparency that means client should see both of leaf and composite in the same manner but this approach violate Lyskov principal in SOLID .

There are another implementation that moves methods to child's side for guarantee safty .

Both of them are acceptable and mentioned in books and each of them as I indicates has cons and pros.

akbar
  • 625
  • 6
  • 12