繁体   English   中英

没有工厂的情况下应将策略模式置于何处?

[英]Where should be placed switch in strategy pattern without factory?

在任何策略模式示例中的Main函数中都可以创建每个可能的策略,例如:

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);
    }
}

最灵活的方法是尽可能长地延迟决策(“切换”)。 例如,如果您从以下内容开始:

Context cn = new Context(); // Don't care about the sorter yet...
cn.Sort(new CQuickSorter(), myList); // OK, NOW the sorter is needed, let's inject it now.

您可以在调用object.Sort()之前的任何时候做出决定。 该决定可以在一个简单的if-else块中,也可以在一个复杂的工厂中实施。 归根结底,最佳实施将取决于项目的复杂性。 因此,没有硬性规则定义应将开关放置在何处。

作为练习,您可以应用各种创建模式来查看它们如何发挥作用。 这将帮助您了解何时使用每种设计模式。

应用依赖项注入时 ,应实例化领域对象并将其绑定到合成根目录中 (即提供其依赖项,例如策略)。 用现代的实用术语来说,这意味着您的DI容器将实例化并根据配置为上下文(客户端)对象提供策略。 没有switch

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM