I have an engine that creates strategies for text file processing. These files are in various formats and the engine selects an appropriate strategy by passing the file through a chain of strategies until one of them asserts it can parse it.
This is not quite the classic strategy pattern. It's somewhat similar to the Service Locator Pattern and Chain Of Responsibility patterns, and could incorporate aspects from any of them.
Stripped down it looks a bit like this, although it's currently created with injection:
public class EngineImpl {
private Set<Strat> strategies = new HashSet<Strat>();
public EngineImpl(){
registerStrategy(new ConcreteStrat1());
registerStrategy(new ConcreteStrat2());
}
public void registerStrategy(Strat strat){
strategies.add(strat);
}
public Strat getStrategy(SomeClass input){
for (Strat s: strategies)
if (s.canParse(input)
return s;
return null;
}
}
As it stands, the problem is that the EngineImpl must know all the available strategies at compile time for this to work and I'd like to be able to deploy new strategies without changing the EngineImpl code. I've looked elsewhere for options to do this in Java and come up with blanks. I considered making Strat classes register themselves with the Engine, but they would never get loaded by the classloader and so would never get the chance to register.
What alternative methods could I use to register strategies? Although I'm currently using DI I'm open to other reflection and/or annotation based solutions.