Question

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?

Was it helpful?

Solution

. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top