以下是对策略的错误使用
interface FilterStrategy {
public void filter();
}
class OldProductsStrategy implements FilterStrategy {
public filter();
}
class NewProductsStrategy implements FilterStrategy {
public filter();
}
class ProductsFilterStrategy {
public getFilter(a) {
if(a) {
return new NewProductsStrategy();
} else {
return new OldProductsStrategy();
}
}
class Client {
new ProductsFilterStrategy().getFilter(true).filter();
}
是否委派战略模式的战略实施部分的选择?
答案 0 :(得分:0)
用法很好。但从技术上讲,负责创建不同实例的类是工厂。不属于战略模式。
答案 1 :(得分:0)
由你决定如何采用这种模式。但在采用和实施模式时,要牢记模式的方法有很多优点。
根据模式定义,您应该有一个Context类:
这样你就可以提供这样的用法:
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
您可以使用工厂或IoC容器提供策略实例。它不是Context的一部分。
答案 2 :(得分:0)
示例是通过静态工厂提供策略层次结构的有效代码。看起来不错。上述代码中仅缺少表示策略模式中上下文的类。
如果策略是无状态的,为什么每次都要创建新策略,那么可以从池中共享这些策略。