【发布时间】:2019-02-19 10:24:05
【问题描述】:
在任何策略模式示例中,主函数中都有创建每个可能的策略,例如:
Context cn = new Context(new CQuickSorter());
cn.Sort(myList);
cn = new Context(new CMergeSort());
cn.Sort(myList);
但是在某些地方我们必须选择我们应该使用什么策略,我们应该在哪里放置“开关”来选择正确的策略?在一个方法?我看到了带有“switch”方法的类,它返回了 OBJECT——正确的策略类实例,但那是工厂,而不是策略模式。
没有工厂的策略模式中应该在哪里“切换”?我有类似下面的方法 - 可以吗?
enum Operation
{
Addition,
Subtraction
}
public interface IMathOperation
{
double PerformOperation(double A, double B);
}
class AddOperation : IMathOperation
{
public double PerformOperation(double A, double B)
{
return A + B;
}
}
class SubtractOperation : IMathOperation
{
public double PerformOperation(double A, double B)
{
return A - B;
}
}
class CalculateClientContext
{
private IMathOperation _operation;
public CalculateClientContext(IMathOperation operation)
{
_operation = operation;
}
public double Calculate(int value1, int value2)
{
return _operation.PerformOperation(value1, value2);
}
}
class Service
{
//In this method I have switch
public double Calculate(Operation operation, int x, int y)
{
IMathOperation mathOperation = null;
switch (operation)
{
case Operation.Addition:
mathOperation = new AddOperation();
break;
case Operation.Subtraction:
mathOperation = new SubtractOperation();
break;
default:
throw new ArgumentException();
}
CalculateClientContext client = new CalculateClientContext(mathOperation);
return client.Calculate(x, y);
}
}
【问题讨论】:
-
谁说工厂不能提供战略?
-
所以没有目的只使用纯策略,因为带有策略的工厂要优雅得多。
-
如果应该避免使用工厂,那么解决方案是 (1) 在策略上添加一个方法,指示该策略支持的操作 (2) 拥有一个包含所有策略的集合 (3) 其中需要使用策略迭代策略集合并找到支持该操作的策略并使用它
-
这不是他们中哪一个更适合的问题,因为两者都有不同的用途。具体策略定义“如何做事”,工厂定义“使用哪种策略”。但是,您不需要工厂来创建策略。
-
话虽如此,但没有通用的解决方案使用哪种模式以及如何使用。
标签: java c# design-patterns