Can the Strategy pattern be implemented without significant branching?
Yes, by using a hashmap/dictionary where every StrategyimplementationStrategy implementation registers at. The factorymethodfactory method will become somthingsomething like
Class strategyType = allStrategies[orderType];
return runtime.create(strategyType);
Every strategy implementation must register a the the factory with its orderType and some information how to create a class.
factory.register(NEW_ORDER, NewOrder.class);
You can use the static constructor for registration, if your language supports this.
The register method does nothing more than adding a new value to the hashmap:
void register(OrderType orderType, Class class)
{
allStrategies[orderType] = class;
}
[update 2012-05-04]
This soulutionsolution is much more complex than the original "switch solution" which i would prefer most of the time.
However in an environment where strategies changes often (i.e. price calculation depending on customer, time, ....) this hashmap solution combined with an IoC-Container could be good solution.