adamo94 adamo94 - 2 months ago 21
C# Question

C#, patterns - many conditions

I am looking for a good pattern for my problem.

I have some bool variables:

condition1, condition2,condition3.

Also I have some actions, which are called in different places inside class:

action1,action2,action3

Action1 is called when conditions 1 and 2 are true.
action2 is called when conditions 2 and 3 are true.
Action 3 is called when all conditions are true.

Of course this is just a simplification of the problem. I don't want to use if else in every place. It is terribly unclear.

I have been thinking about state but I guess it's not best solution for this problem.

Answer

One option is to wrap the condition logic in a base class and then derive from it to execute the actual actions. The is a variation on the Command pattern and (I think) the Strategy pattern:

class ActionState
{
  public bool Condition1{get;set;}
  public bool Condition2{get;set;}
  public bool Condition3{get;set;}
}

abstract class ActionDispatcher
{
  protected abstract void ExecuteAction1();
  protected abstract void ExecuteAction2();
  protected abstract void ExecuteAction2();

  public void Action1(ActionState state)
  {
    if(state.Condition1 && state.Condition2)
    {
      ExecuteAction1();
    }
  }

  public void Action2(ActionState state)
  {
    if(state.Condition2 && state.Condition3)
    {
      ExecuteAction2();
    }
  }

  public void Action3(ActionState state)
  {
    if(state.Condition1 && state.Condition2 && state.Condition3)
    {
      ExecuteAction3();
    }
  }

  public void AllActions(ActionState state)
  {
    // Execute all actions depending on the state
    Action1(state);
    Action2(state);
    Action3(state);
  }
}
Comments