Frage

In Composite design pattern we handle the hierarchies in the manner as shown in the UML below.

Composite design pattern

But when you look at the Leaf class in the above figure you see it has empty implementations of addComponent, removeComponent and getChild since these methods do not apply for the Leaf node. What i really need to know is that is there any way around that we don't have to implement empty/no-op methods?

Update : Ok, i removed the Liskov's principle part since it's now clear to me. But it still does not clarify why the Leaf node need to force-implement the three methods and is there a way that it does not have to? I think there is another principle that states that subclasses should not be forced to implement methods which are unnecessary. My main concern are implementation of three methods for the Leaf node and you can think about this scenario in any parent-child structure, not necessarily Composite pattern.

War es hilfreich?

Lösung

The addComponent() removeComponent() and getChild() methods only make sense for a Composite. Thus they should not be declared in the Component's API.

Nevertheless the empty implementations in the Leaf do not break the Liskov's substituation principle as long the Leafs will behave as the Component defines it. I think this will be true in your case.

Furthermore you can find a good example of how a composite pattern can be implemented in java swing. Take a look at java.awt.Component and java.awt.Container.

EDIT

What i really need to know is that is there any way around that we don't have to implement empty/no-op methods?

Make the Component an abstract class instead of an interface and implement the no-op methods for addComponent() removeComponent() and getChild() there.

public abstract class Component {

     public abstract doOperation(); // still need to be implemented by subclasses


     /**
      * Empty stub method. Subclasses may override it.
      */
     public void addComponent(Component comp){
     }

     public void removeComponent(Component comp){
     }

     public Component getChild(int index){
         return null;
     }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top