我有以下的策略模式实现:使用工厂创建一个策略
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>();
}
}
我的客户端应用程序接收无论是速度还是从用户的限制(可能还有其它参数)。我想创建一个工厂类,它将返回基于具有值的参数和不具有参数的适当策略。我不希望客户决定应该返回哪个策略。如果工厂createStrategy(params)
方法对每个参数都有if
语句,并且取决于不同的组合(假设还有其他策略类),那么返回具体策略类? 这样做的正确方法是什么?
这就是我会做的。你有什么疑问? – 2012-03-25 16:31:04
很难延伸。 – 2012-03-25 16:34:30
TBH,这听起来像是一个非OO维护的噩梦,让工厂使用“is-parameter-set”启发式来猜测使用哪种策略。如果你最终得到两个使用完全相同参数的策略呢?您将无法使用此工厂设计。 – 2012-03-25 16:38:18