需求:设备监控功能,设备状态有多种,并且可能增加、修改等。
所以我将各种状态都划分出来,设计如下:
StateJudgeFaction——状态判断对象生产工厂
StateJudge——状态判断类
StateA——状态A类
StateB——状态B类
StateC——状态C类
……
StateA、StateB、StateC都继承StateJudge类,StateJudge类中有抽象方法IsNormal()判断状态是否正常
设计代码如下:
- C# code
class StateJudgeFaction { public static StateJudge CreateStateJudge() { StateJudge sj = null; return sj; } } class StateJudge { protected virtual void IsIsNormal() { //判断状态是否正常代码 } } class StateA : StateJudge { protected override void IsIsNormal() { //判断状态是否正常代码 } } class StateB : StateJudge { protected override void IsIsNormal() { //判断状态是否正常代码 } } class StateC : StateJudge { protected override void IsIsNormal() { //判断状态是否正常代码 } }
因为经常听说,设计与显示分离,上面的只是设计功能上的问题,但是实际上他们都需要一些数据用来操作,最后显示或者返回。
因为StateJudgeFaction类中的CreateStateJudge()函数需要状态和其他计算数据才能运算,现在我想把需要的数据包装成一个类——CarFreeRegion空闲时间段类,
- C# code
class CarFreeRegion { private DateTime startDate;//空闲时间段开始时间 public DateTime StartDate { get { return startDate; } set { startDate = value; } } private DateTime endDate;//空闲时间段结束时间 public DateTime EndDate { get { return endDate; } set { endDate = value; } } private string carPlan;//车牌号码 public string CarPlan { get { return carPlan; } set { carPlan = value; } } private string simNo;//sim编号 public string SimNo { get { return simNo; } set { simNo = value; } } private string canUseModel;//用车方式 public string CanUseModel { get { return canUseModel; } set { canUseModel = value; } } private string useNo;//用车单号 public string UseNo { get { return useNo; } set { useNo = value; } } private string carState;//车辆处理后的状态 public string CarState { get { return carState; } set { carState = value; } } }
最后代码改成如下:
- C# code
class StateJudgeFaction { public static StateJudge CreateStateJudge(CarFreeRegion cfr) { StateJudge sj = null; switch (cfr.CanUseModel) //车辆状态 { case "StateA": sj = new StateA(cfr); break; case "StateB": sj = new StateB(cfr); break; case "StateC": sj = new StateC(cfr); break; default: break; } return sj; } } class StateJudge { CarFreeRegion cfr = null; public StateJudge(CarFreeRegion cfr) { this.cfr = cfr; } protected virtual void IsIsNormal() { //判断状态是否正常代码 //通过炒作cfr对象返回或显示数据 } } class StateA : StateJudge { public StateA(CarFreeRegion cfr) : base(cfr) { } protected override void IsIsNormal() { //判断状态是否正常代码 } } class StateB : StateJudge { public StateB(CarFreeRegion cfr) : base(cfr) { } protected override void IsIsNormal() { //判断状态是否正常代码 } } class StateC : StateJudge { public StateC(CarFreeRegion cfr) : base(cfr) { } protected override void IsIsNormal() { //判断状态是否正常代码 } }