本文主要是介绍【C#重构】——上机余额判断应用的 状态模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
回顾状态模式:
根据不断的请求或者实时变化,更改状态
可对状态进行读取并更具判断,设置新的状态
不同的子状态重写抽象类状态,进行实时判断更改。
实战分析:
在上机中,要进行实时地余额判断,并进行余额不足和小于最低余额强制下机的操作
或许实时的余额变化,进行判断余额调整状态。
Sate类
public class StateModel{public abstract class State{public abstract string WriteProgram(Context context);}public class Context{//用到的实体private State current;private double consume;public double Consume { get => consume; set => consume = value; }public State Current { get => current; set => current = value; }public void SetState(State s)//改变初始状态,可读当前状态{Current = s;}public string WriteProgram()//请求的处理,并设置下一个状态{string a = Current.WriteProgram(this);return a;}public class StateOne : State//具体子状态1{public override string WriteProgram(Context context){string a = "null";if (context.Consume >= 10){a = "null";}else{context.SetState(new StateTwo());context.WriteProgram();}return a;}}public class StateTwo : State//具体子状态2{public override string WriteProgram(Context context){string a = "null";if (context.Consume < 10){a = "余额不足10元,请尽快充值,以免影响上机!";}else{context.SetState(new StateThree()); context.WriteProgram();}return a;}}public class StateThree : State//具体子状态3{public override string WriteProgram(Context context){string a = "null";if (context.Consume < 5){a = "余额不足5元,正在下机";}return a;}}}
外观层进行传值
//连接状态模式public string InquireyStat(LineInfo outline){StateModel.Context cs = new StateModel.Context();cs.Consume = outline.Cash;string a = cs.WriteProgram();Entity.Gloable.Time++;return a;}
UI层判断
private void txtOnUserID_EnabledChanged(object sender, EventArgs e){if (txtOnUserID.Enabled == false)//当确定用户已上机,则启动状态模式,实时判断余额情况{timerOut.Enabled = true;//计时器开始运行timerOut.Start();//启动计时器 }}private void timerOut_Tick(object sender, EventArgs e){//student 表 selectEntity.StudentInfo student = new Entity.StudentInfo();student.UserID = Convert.ToInt32(txtOutUserID.Text.Trim());DataTable table1;Facade.OutLineFacade facade = new Facade.OutLineFacade();table1 = facade.SelectStudentFacade(student);//line_info表,插入上下机记录表 insertEntity.LineInfo outline = new Entity.LineInfo();int balance = Convert.ToInt32(table1.Rows[0][2].ToString());//学生表余额outline.Consume_time = Convert.ToString(Gloable.Time);//??//每一小时查看余额string a = facade.InquireyStat(outline);if (a == "null"){return;}else{MessageBox.Show(a, "提示");if (a == "余额不足5元,下机"){//调用下事件btnOutLogin_Click(sender, e);timerOut.Start();}}}
还有不完善的地方,多指正
这篇关于【C#重构】——上机余额判断应用的 状态模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!