根据某些设置调用方法?

时间:2011-05-02 14:16:18

标签: c# design-patterns conditional

我有一些看起来像这样的代码:

if(someCondition)
{
    SomeClass1.DoSomething();
    SomeClass2.DoSomethingElse();
    SomeClass3.DoSomethingElseAgain();
}

if(someOtherCondition)
{
    SomeClass4.WhatEver();
}

现在,有时候应该调用所有这些方法,有时只调用一些方法。例如,有时我只想打电话

SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();

不应该打电话给其他人。是否有一个很好的模式或技巧来实现它?

谢谢: - )

3 个答案:

答案 0 :(得分:3)

您可以创建List<Action>,并针对每个条件(if(someCondition)部分),将要调用的方法添加到操作列表,然后在结束循环中添加通过行动并执行每一个。

如果您的方法与Action<T>模式不匹配(零或一个参数,不返回值),您可以创建另一个以相同方式起作用的自定义委托。

这里有一些伪代码:

static void Main(string[] args)
{
    List<Action> actionList = new List<Action>();

    if (true)
    {
        actionList.Add(new Action(DoSomething));
    }
    // etc.

    foreach (Action a in actionList)
    {
        a();
    }
}

static void DoSomething()
{
    // Code to do something.
}

我知道这似乎是一个更长,更复杂的方法,从OP的帖子中做if / else方法,但在某些情况下,这实际上可能是一个更好的设计(只是不是所有情况)。由于OP太模糊,所以很难知道什么会有效。

答案 1 :(得分:3)

策略模式在这种情况下会很好用:http://en.wikipedia.org/wiki/Strategy_pattern

示例:

class StrategyExample {

    public static void main(String[] args) {

        Context context;

        context = new Context(new SomeCondition());
        context.executeStrategy();

        context = new Context(new SomeOtherCondition());
        context.executeStrategy();
    }
}

// The classes that implement a concrete strategy should implement this. The context class uses this to call the concrete strategy
interface Strategy {
    void DoSomething(); 
}

// Implements the algorithm using the strategy interface
class SomeCondition implements Strategy {

    public void DoSomething() {
        // some condition code
    }
}

// Implements the algorithm using the strategy interface
class SomeOtherCondition implements Strategy {

    public void DoSomething() {
        // dome other condition code
    }
}

// Configured with a concrete strategy object
class Context {

    private Strategy strategy;

    // Constructor
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public void executeStrategy() {
        strategy.DoSomething();
    }
}

答案 2 :(得分:-1)

我认为您可以使用下面的开关案例块,

开关(ext.ToLower())             {                 案例“.htm”:                 案例“.html”:                     type =“text / HTML”;                     打破;

            case ".txt":
                type = "text/plain";
                break;

            case ".doc":
            case ".rtf":
                type = "Application/msword";
                break;
            case ".xls":
                type = "application/vnd.ms-excel";
                break;
            case ".xlsx":
                type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                break;
        }