Strategy Design Pattern, Generics and TypeSafety

前端 未结 3 2194
忘掉有多难
忘掉有多难 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 02:00

    I'd simply pass a Parser to the getResults() method and forget about that factory stuff. Look, if you say:

    public  Parser createParser(ParserType typ) { ... }
    

    you are promising that the method will create a parser of any type the caller wants. This is only possible in a type safe way with parsers that all return an empty collection. Moreover, you can't return a Parser from that function, because String is not the same as any type the caller wanted.

    If, however, you write:

      public  Collection getResults(String query, Parser parser) {
          ResultSet resultSet = getResultSet(query); //local private method
          Collection results = parser.parse(resultSet);
          return results;
      }
    

    you have exactly what you wanted: the getResult method is independent of how the parser works, and yet it returns a collection of the correct type.

    And later, instead of

    Collection it = (Collection) getResults("query", APARSER);
    

    you say:

    Collection it = getResults("query", new AParser());
    

    This is sound and makes sense.

提交回复
热议问题