2011-05-02 9 views
0

私はこのようになりますいくつかのコードがあります。今いくつかの設定に応じてメソッドを呼び出しますか?

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

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

を、時にはすべてのこれらのメソッドのは一部だけ時々、呼ばれるべきです。たとえば、ときどき私は電話したいだけです。

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

残りを呼び出すことはできません。それを達成するための良いパターンやトリックはありますか?あなたはList<Action>を作成し、条件(if(someCondition)部分)のそれぞれについて、あなたはアクションリストに呼び出したいメソッド(複数可)を追加し、最後にでき

+1

if-elseの問題点は何ですか? –

+0

何もないが、if/elseをあまりにも多く避けたかった。いいパターンや何かがあることを期待していましたか? – grady

答えて

3

Strategyパターンは、このような状況で素敵な仕事になります。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(); 
    } 
} 
+0

+1あなたは私より速いです... – rsenna

3

:-)

感謝アクションをループして、それぞれを実行します。

メソッドがAction<T>パターン(ゼロまたは1つのパラメータで値を返さない)と一致しない場合、同じ方法で動作する別のカスタムデリゲートを作成できます。ここ

とは、あなたのためにいくつかの擬似コードです:

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のポストからの場合/他のアプローチを行う長く、より複雑な方法のように思えるが、知っているいくつかのケースでは、これは実際に可能性がありより良いデザイン(すべてではない)。 OPが非常に曖昧だったので、何がうまくいくかを知ることは難しいです。

-1

スイッチ(ext.ToLower() ) { case ".htm": case ".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; 
     } 
+0

スイッチ節の提案は良い考えではありません。スイッチを省略して、答えがわかりやすいソリューションに近づけないようにしてください。 – dzendras

関連する問題