I want to create the following Strategy Pattern combined with Factory, but I want it to be typesafe. I have done the following till now:
public interface Parser&
I usually use this format. I know that a lot of people does not like it but no one suggested a better approach so far.
public enum ParserType {
APARSER(new AParser());
private Parser parser; // this should be an interface which is implemented by AParser
private ParseType(Parser parser){
this.parser = parser;
}
public Parser getParserInstance() {
return parser;
}
}
You can pass Class
objects around if you want a new instance every time:
public enum ParserType {
APARSER(AParser.class);
private Class parserClass;
private ParseType(Class parserClass){
this.parserClass = parserClass;
}
public Parser createParser() {
return parserClass.newInstance(); // TODO: handle exceptions here
}
}
Note: I'm eager to find a better approach so if you have some thoughts please share them in a comment.