簡體   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