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 Leaf
s 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;
}
}