سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

Design Patterns are often combined. I think the fact that most Pattern books show each one separately is misleading to people learning about them.

Your example is a little vague so it's a little hard to fully understand what you mean, however I think factoring out the execute() function into a separate interface to turn it into a Strategy and allowing that Strategy to be injected into Class A (the root of the composite) is one solution. Class A can then inject the strategy to the other objects that are being composited.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top