jeudi 28 janvier 2016

How to inherit state from multiple classes?

I have a composite like pattern in where there is different functionality for the roots of the trees, branches and leafs. The problem is that there is a shared state between both Root with Branch and Branch with Leaf. I'm searching for the cleanest solution which prevents code duplication.

Diagram

The functionality among root, branch and leaf all relate to the same set of methods (though leaf has different signatures).

  • Embeddable interface implicates that the implementation has a parent and some mutable properties.
  • Composite has Embeddable children and provides abstract functionality methods for which Root and Branch have their separate implementations.
  • Root is the actual executor of most functionality.
  • Branch will most often - but not always - pass information to its parent with modified parameters.
  • Leaf can appear both on the root and branches and has fewer functionality methods with smaller method signatures. Will always pass its calls to its parent with extra parameters. It is stored explicitly in every Composite where it is created and loaded lazily.

Shared state

  • Root and Branch's shared state is in this case solved by Composite.
  • The Embeddable interface enforces that Branch and Leaf provide its behavior.

The problem the implementation is the same for Branch and Leaf and implementing it would cause duplicate code. It's impossible to make Embeddable an abstract class because Branch already extends Composite.

I'm searching for a pattern or general solution so that Branch can share state with Embeddable and Composite at the same time. Basically a multiple-inheritance workaround.

Aucun commentaire:

Enregistrer un commentaire