Search code examples
design-patternscompositestrategy-pattern

combining strategy and composite pattern


I would like to combine two design patterns in my software. I have first created a composite pattern, modeling my business problem.

enter image description here

Thus with this, I model the structure of my problem well, and an object tree will be created. I want to run some business logic on this (say execute function, which returns a number of elements). But this algorithm needs to be adjustable on high level. ie I want to be able to change the execute functions for all the classes shown in the picture.

I am looking for some usefull documentation and/or tips! Any ideas?


Solution

  • I don't see a Composite pattern working well with components being objects of heterogeneous types that don't share a common ancestor. You need all the components to inherit some kind of Component class, possibly with Composite and Leaf subclasses to specify a general behavior for leaves and nodes.

    How can A know what to inject in C/E? It only knows that it has children of the 'conceptual class'

    A shouldn't know it has children of the 'conceptual class'. It should only know it has Component children. C and E are the ones who know they are of the 'conceptual class'. Depending on your language, this double nature of C and E might be tricky to implement (no multiple inheritance, etc.)

    Can you provide details on how the fact that Class E and Class C derive from a "conceptual superclass" interferes with the whole composite / execute() / strategy thing ? Without that knowledge, it's hard to recommend anything.