Search code examples
design-patternsdependency-injectionstrategy-pattern

Strategy Pattern with default strategy


I'm kind of a beginner when it comes to design patterns. Any thoughts on implementing the strategy pattern/ like this:

public class SomeClass {

    private Strategy strategy = new DefaultStrategy();

    public void provideCustomStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
}

This will ensure loose coupling and all the other benefits of the Strategy Pattern and DI. At the same time you don't force the user to provide a strategy, and the user can decide to provide a custom strategy for corner cases, etc. One can achieve the same goal with constructor-injection if you provide a constructor with a Strategy-parameter. I think this implementation will provide maximum flexibility in many cases.


Solution

  • The downside of this approach is that you have a permanent coupling to the DefaultStrategy class. If that brings any significant baggage with it you may regret this in the future.

    An alternative might be to use some kind of late-binding. So you don't have a default strategy, instead you have the name of a default strategy. At runtime, on first use, we look up the name a load the corresponding class. Now we have the option of controlling the strategy by adjusting the name-class mapping.

    This is one possibility enabled by JEE's resource lookup in JNDI.