做一个Winform程序,因为存在好几种状态,比如normal mode,debug mode,raster mode等等七八种状态,
所以想做成state模式。可具体实施的时候,发现不是很好。
比如我做一个State父类然后一个NormalState,DebugState子类,然后在不同的State下,主窗口需要显示不同的数据,和绘制不同的图案以及更新一些lable标签等,为了实现这些功能,所以我把Form类传递给State类,问题来了...如果让State类来实现这些主窗口的更新,那么Form类必须把PictureBox,Lable,TextBox这些成员做成public属性,而且由其他类来控制Form类的这些成员变量的行为,总感觉不是太合适。
如果这些更新放在Form类里面,做成函数比如NormalDraw()这样,然后由NormalState的Draw()函数调用Form.NormalDraw(),感觉也不好。因为这种写法好像很拖沓。我宁愿在Form里面维护一个KeyValuePair的List,Key就是状态,Value就是具体Draw函数的delegate。这样,查询到什么key,就调用什么draw函数,感觉反而比一大堆state类的调用更清晰。不知道上面说清楚没有...其实就是三种方式,以NormalMode的NormalDraw(),来举例。
第一种:
class NomalState
{
public void Draw(Form form)
{form.pictureBox.Draw();
form.textBox.Draw();
form.lable.Draw()}}class Form
{private void Draw()
{_state.Draw()}}第二种:class NormalState{public void Draw(Form form)
{form.NormalDraw();}class Form{
public NormalDraw()
{this.pictureBox.Draw();
this.textBox.Draw();
this.lable.Draw()}private Draw()
{
_state.Draw();
}
}第三种,不用state模式,匹配的方式:class Form
{
List<KeyValuePair<string, StateHandler>> _parseList;//string 决定状态,StateHander是一个delegate
Form()
{
_parseList.add(normalString, NormalDraw);
_parseList.add(debugString, DebugDraw);
}private void Draw()
{
foreach (KeyValuePair<string, StateHandler> pair in _parseList)
      {
if (_stateString == pair.Key) //查询当前状态,调用相应delegate,normalString就调用NormalDraw();
{
pair.Value();
}
      }
}private void NormalDraw()
{this.pictureBox.Draw();
this.textBox.Draw();
this.lable.Draw()}
}
我个人感觉第三种方式,不用state,反而好像最清晰一点,封装也最好...