Alternative Pattern to Strategy
I have a piece of code where I started to put the strategy pattern in place, say as follows:
IStrategy
StrategyA : IStrategy
StrategyB : IStrategy
StrategyC : IStrategy
The interface just has a Calculate method on it. After implementing, it turned out that all 3 concrete types had identical code for the Calculate method and two identically named Properties, just with different values set.
So to remove duplication I made the interface an abstract class and moved the method and properties down to that, just setting the base properties with their respective values from within construction of the concrete types.
Now I know patterns aren't hard and fast rules, merely guidelines开发者_如何学JAVA, but I've warped this so far from the guidelines that I can't help but think there's another pattern I should be looking at?
Can anyone suggest any other approaches please, that leave me so it would be easy to add on new 'Strategies' down the line. It may turn out that we need to alter the logic in some of these new cases, so how could I structure that so I don't have repeating code, but have a flexible design that lets me alter things down the line?
Thanks.
Why don't you create a abstract class BaseStrategy
class that has all the common functionality, and extend it in all concrete strategies?
Other alternative you can use is Template pattern. But it has problem: it does allow you to change the algorithm for the new cases but in a very limited way.
So if flexibility is your aim, Strategy is still the best answer and you are correctly right to create an abstract class for the common case.
Its hard to make assumption on paterns with knowing almost nothing about your business logic, but I would suggest to consider Builder pattern that lets you extract some code to abstract class and have sublasses have implement particular logic combined with Visitor patern to extract your algorythm from those concrete implementations classes.
It should naturaly come as you are coding, no patern is going to miraculously solve the goal you are trying to achieve.
Have an interface IStrategy. An abstract class BaseStrategy which implements IStrategy. This way you can extend or implement the interface based on the presence or absence of the common code and the client can refer to the interface
精彩评论