Strategy Design Pattern, Generics and TypeSafety

前端 未结 3 2191
忘掉有多难
忘掉有多难 2021-02-09 01:25

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&         


        
3条回答
  •  天涯浪人
    2021-02-09 01:50

    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.

提交回复
热议问题