0

I'm implementing 2 different concrete strategies using the Strategy Design Pattern, and the second heavily reuses code from the first, while expending on it. I am wondering whether this "breaks" the advantages of the strategy design pattern, or whether this makes any difference? Is there a better way to do this, such as having an abstract class implement the strategy interface, and have the two strategies inherit from that abstract class?

Another way to look at this question is: Do the Strategy Design Pattern's advantages stem from the fact that different strategies can be added and removed without impact on any of the other strategies? If so, should I copy the code over to the more complex concrete strategy?


In my particular case, I'm implementing two different essay sorter strategies:

  1. The first sorts all essays based on how similar they are to certain keywords.

  2. The second strategy sorts all authors first, then sorts calls the first concrete strategy to sorts each author's essays based on how similar they are to the keywords.

Is this an appropriate design?

  • What about aggregating the simple strategy into the more complex one? – raina77ow Oct 27 '13 at 20:46
  • I edited the question to clarify exactly what I'm asking - the answer to the (newly added) second paragraph will determine whether aggregating strategies will make sense. – insertjokes Oct 27 '13 at 20:54
  • 2
    I still think it's easier to use composition to bridge the gap between two strategies. Check [this answer](http://stackoverflow.com/questions/13842420/combining-composite-and-strategy) to see how it can be done. – raina77ow Oct 27 '13 at 21:08
  • Totally agree with @raina77ow and I think the answer he links to is spot on. The design is far more modular if the two strategies are implemented separately as they can be used individually or combined with each other (or other strategies) in different orders. – net.uk.sweet Oct 27 '13 at 23:03
  • common behavior can be moved to base abstract class – zzfima Nov 07 '13 at 18:13

1 Answers1

0

. I am wondering whether this "breaks" the advantages of the strategy design pattern, or whether this makes any difference?

Copying code is bad; if you have to fix it in one place, then chances are that you will forget to copy the fix into all copies. Think of the poor soul who has to support this mess!

If the strategies have common code then you can either

  • put common code into a utility class and add aggregate / add the common class as member of both implementations,

  • put common code into a base class and inherit this class in both implementations

Aggregation is usually favored over inheritance.

MichaelMoser
  • 3,172
  • 1
  • 26
  • 26