I have the following Strategy Pattern implemented:
public abstract class RetrievalStrategy {
public abstract List<MyObject> retrieve();
}
public class LimitRetrievalStrategy extends RetrievalStrategy {
public int limit;
public LimitRetrievalStrategy(int limit) {
this.limit = limit;
}
public List<MyObject> retrieve() {
// fill up the list and return it, limiting to 'limit' results
return new ArrayList<MyObject>(limit);
}
}
public class SpeedRetrievalStrategy extends RetrievalStrategy {
public int speed;
public SpeedRetrievalStrategy(int speed) {
this.speed = speed;
}
public List<MyObject> retrieve() {
// do something with the speed and return list again
return new ArrayList<MyObject>();
}
}
My client application receives either a speed or a limit (and perhaps other parameters) from the user. I want to create a factory class that will return the proper strategy based on parameters that have a value and parameters that don't. I don't want the client the decide which Strategy should be returned. Should the factory createStrategy(params)
method then have if
statements for each parameter and depending on the different combinations (imagine there are other Strategy classes) return the Concrete Strategy class?
What is the proper way to do this?
No, the return value in the method signature should be the common interface or base class.
The factory must have the if tests to decide on the concrete type to return, but that's unavoidable, unless you can craft a Map that returns a concrete instance based on a composite key class that encapsulates parameter combinations.