avoiding if statements

前端 未结 24 1049
心在旅途
心在旅途 2021-01-30 08:39

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you ca

24条回答
  •  没有蜡笔的小新
    2021-01-30 09:37

    Have a look at the Anti-If Campaign The idea is not to replace every single if in your application with the Strategy or State Pattern. The idea is that when you have complex branching logic especially based on something like an enumeration, you should look to refactoring to the Strategy Pattern.

    And that case you can remove the if all together by using a Factory. Here is a relatively straightforward example. Of course as I said in a real case, the logic in your strategies would be a bit more complex than just printing out "I'm Active".

    public enum WorkflowState
    {
      Ready,
      Active,
      Complete
    }
    
    public interface IWorkflowStrategy
    {
      void Execute();
    }
    
    public class ActiveWorkflowStrategy:IWorkflowStrategy
    {
      public void Execute()
      {
        Console.WriteLine("The Workflow is Active");
      }
    }
    
    public class ReadyWorkflowStrategy:IWorkflowStrategy
    {
      public void Execute()
      {
        Console.WriteLine("The Workflow is Ready");
      }
    }
    
    public class CompleteWorkflowStrategy:IWorkflowStrategy
    {
      public void Execute()
      {
        Console.WriteLine("The Workflow is Complete");
      }
    }
    
    public class WorkflowStrategyFactory
    {
      private static Dictionary _Strategies= 
        new Dictionary();
      public WorkflowStrategyFactory()
      {
        _Strategies[WorkflowState.Ready]=new ReadyWorkflowStrategy();
        _Strategies[WorkflowState.Active]= new ActiveWorkflowStrategy();
        _Strategies[WorkflowState.Complete] = new CompleteWorkflowStrategy();
      }
      public IWorkflowStrategy GetStrategy(WorkflowState state)
      {
        return _Strategies[state];
      }
    }
    
    public class Workflow
    {
        public Workflow(WorkflowState state)
        {
            CurrentState = state;
        }
        public WorkflowState CurrentState { get; set; }
    }
    
    public class WorkflowEngine
    {
        static void Main(string[] args)
        {
            var factory = new WorkflowStrategyFactory();
            var workflows =
                new List
                    {
                        new Workflow(WorkflowState.Active),
                        new Workflow(WorkflowState.Complete),
                        new Workflow(WorkflowState.Ready)
                    };
            foreach (var workflow in workflows)
            {
                factory.GetStrategy(workflow.CurrentState).
                    Execute();
            }
        }
    }   
    

提交回复
热议问题