Note that there are some explanatory texts on larger screens.

plurals
  1. POStrategy Design Pattern, Generics and TypeSafety
    primarykey
    data
    text
    <p>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:</p> <pre><code>public interface Parser&lt;T&gt; { public Collection&lt;T&gt; parse(ResultSet resultSet); } public class AParser implements Parser&lt;String&gt; { @Override public Collection&lt;String&gt; parse(ResultSet resultSet) { //perform parsing, get collection Collection&lt;String&gt; cl = performParsing(resultSet); //local private method return cl; } } public class ParserFactory { public enum ParserType { APARSER } public static &lt;T&gt; Parser&lt;T&gt; createParser(ParserType parserType) { Parser&lt;?&gt; parser = null; switch (parserType) { case APARSER: parser = new AParser(); break; } //unchecked cast happens here return (Parser&lt;T&gt;) parser; } } public class Context { public &lt;T&gt; Collection&lt;T&gt; getResults(String query, ParserType parserType) { ResultSet resultSet() = getResultSet(query); //local private method Parser p = ParserFactory.createParser(parserType); Collection&lt;T&gt; results = p.parse(resultSet) } } </code></pre> <p>In general whatever I attempt, somewhere I will have an unchecked cast. Anyone have an idea how I can refactor the code to be typesafe?</p> <p>Checking Effective Java I also stumbled upon this pattern:</p> <pre><code>public final class ParserFactory { private ParserFactory() { } private static class AParser implements Parser&lt;String&gt; { @Override public Collection&lt;String&gt; parse(ResultSet resultSet) { //... return new ArrayList&lt;&gt;(); } } public static final Parser&lt;String&gt; APARSER = new AParser(); } </code></pre> <p>So now I can use as Ingo suggested</p> <pre><code>public &lt;T&gt; Collection&lt;T&gt; getResults(String query, Parser&lt;T&gt; p) </code></pre> <p>as</p> <pre><code>getResults("query", ParserFactory.APARSER); </code></pre> <p>Or would this be better with enums?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload