Search code examples
javaoopdesign-patternscomposite

How to handle functions for add, delete in composite pattern?


Composite pattern is useful for handling part-whole hierarchies. It has an interface for the Component. Leaf and Composite both provide implementation for the Component interface.

What should be the implementation for Add(Component c), Remove(Component c) and GetChild(int position) methods in Leaf class ?

I can have methods do nothing, or throw an exception like : OperationNotSuportedByLeafException. But Doing this will break the Liskov substitution principle. What is the best way to handle these methods?

Edit: Another approach is moving these methods in Composite. It will be the topmost interface being exposed i.e. Component. Moving the methods in Composite will require explicit casting, when there will be need to call the add, remove operations, which again is against good design principle.

enter image description here


Solution

  • There are two ways to solve this issue.

    1. Throw OperationNotSuportedByLeafException. You can debate if this breaks LSP. Personally I think it should be avoided but sometimes it is the best solution (See Java's immutable lists for example). The LSP is a principle meant to help you write better quality code. Every system has warts and this may be one of them.

    2. Move add & remove to Composite entity (example). This is what you would typically see in a view library. A View may be a block of text or it may be a complex layout full of many other views.