2

Strategy pattern solves the necessity of applying a certain algorithm/behaviour depending on the object's type itself. So you can iterate over a bunch of similar objects and call the same function expecting different algorithms to be executed for each one.

But what about two (or more) objects may have a special algorithm for them together? Only if they both are in our list to iterate. If not, they have their own single object behaviour.

Example:

We have different object types: Blue, Yellow and Red. They all have their own shine() method, which implements from its own strategy: BlueShineStrategy, YellowShineStrategy and RedShineStrategy.

Then I have a combination of Blue and Yellow objects. In order to make them shine, I'll do:

combination = [blueObject, yellowObject]
for c in combination:
   c.shine()

That's okay. The problem comes when a restriction is added. If Red and Blue are present in the combination, I cannot call the shine method for everyone, I must use, just for those two, a RedBlueShineStrategy.

When is the time to ask and decide the use of the combined strategies? Is it in the moment of execution (the for moment)?

Or should I decide this before? (considering I can model the combinations, I can have an array of "special groups" included in the model)

2 Answers2

1

I think the problem is in the name. Calling it RedBlueShineStrategy is too specific. Perhaps MultiColorShineStrategy works better, because you are dealing with the abstraction of multiple colors. This could take an array or colors and it just shines them all.

So I suppose combining the strategy pattern with the composition pattern would work.

1

I think the pattern you want is Visitor. In essence, you need something to operate on an aggregate. So. If you have a hierarchy or collection of things, have a ShineVisitor visit your aggregate. This will allow you to shine through filters for example.

Sentinel
  • 432