Java – Modified Strategy Design Pattern

design-patternsinterfacesjavastrategy

I've started looking into Design Patterns recently, and one thing I'm coding would suit the Strategy pattern perfectly, except for one small difference.

Essentially, some (but not all) of my algorithms, need an extra parameter or two passed to them.

So I'll either need to

  • pass them an extra parameter when I invoke their calculate method

or

  • store them as variables inside the ConcreteAlgorithm class, and be able to update them before I call the algorithm.

Is there a design pattern for this need / How could I implement this while sticking to the Strategy Pattern?

I've considered passing the client object to all the algorithms, and storing the variables in there, then using that only when the particular algorithm needs it. However, I think this is both unwieldy, and defeats the point of the strategy pattern.

Just to be clear I'm implementing in Java, and so don't have the luxury of optional parameters (which would solve this nicely).

Best Answer

You need to clarify your strategy.

It all depends on how you use your algorithms. For your client class to use different strategy implementations interchangeably, they all need to have a common abstraction. If they don't follow the same interface, maybe what you need are different abstractions.

I've used configurable strategies before, where you parameterize the concrete classes on construction:

interface Strategy {
  int calculate();
}

class ConcreteStrategyThatNeedsAParameter implements Strategy {
  private final int param;
  public ConcreteStrategyThatNeedsAParameter(int param) {
    this.param = param;
  }
  public int calculate() { 
    // uses param...
  }
}

Now, someone still needs to create an instance of this class and pass it to your client. But your client still only needs to know about the Strategy interface.

It also works if your strategy method takes parameters, but then your client knows about those parameters and passes them to all implementations it works with.

Related Topic