“取决于工作项的状态”,带来了状态设计模式
无论哪种方式,您都必须重构界面并最终破坏客户合同。
如果我正确理解了您的问题,那么您有一个 WorkItemProcessor,其状态会根据发送给它的 WorkItem 发生变化。
因此你的 WorkItemProcessor 变成
// Context
public class WorkItemProcessor
{
public IState CurrentState { get; set; }
public WorkItemProcessor(IState initialState)
{
CurrentState = initialState;
}
public void Process(WorkItem workItem)
{
CurrentState.Handle(this, workItem);
}
}
然后我们定义 WorkItemProcessor 可能处于的多个状态
// State Contract
public interface IState
{
void Handle(WorkItemProcessor processor, WorkItem item);
}
// State One
public class CompleteState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CompletenessConditionHoldsTrue ? (IState) this : new CancelState();
}
}
// State Two
public class CancelState : IState
{
public void Handle(WorkItemProcessor processor, WorkItem item)
{
processor.CurrentState = item.CancelConditionHoldsTrue ? (IState) this : new CompleteState();
}
}
假设您的 WorkItem 看起来像
// Request
public class WorkItem
{
public bool CompletenessConditionHoldsTrue { get; set; }
public bool CancelConditionHoldsTrue { get; set; }
}
把它们放在一起
static void Main()
{
// Setup context in a state
WorkItemProcessor processor = new WorkItemProcessor(new CancelState());
var workItem1 = new WorkItem { CompletenessConditionHoldsTrue = true };
var workItem2 = new WorkItem { CancelConditionHoldsTrue = true };
// Issue requests, which toggles state
processor.Process(workItem1);
processor.Process(workItem2);
Console.Read();
}
希望这能让你更接近。干杯。