0

我已转向我的netmf项目的状态模式。基于此的一些东西:http://www.dofactory.com/Patterns/PatternState.aspx#_self2如何在状态模式代码中传递中断的本机事件处理程序

我有一个旋转编码器旋钮,在每个状态下的作用会不同。

我一直在试图把我的头围绕这个,并且无法得到任何工作在我的结尾。我不确定在哪里以及如何将中断处理程序注入每个状态以及如何调用中断处理程序的开关。无状态模式的代码看起来是这样的:

RotaryEncoder RE = new RotaryEncoder(pin1, pin2);//create new instance of knob 
RE.OnRotationEvent += OnRotationEventHandler;//subscribe to an event handler. 
//do other things 
... 
... 

static void OnRotationEventHandler(uint data1, uint data2, DateTime time) 
     { 
      //do something 
     } 

那么,什么是正确的方式代码已经为每个国家单独的“OnRotationEventHandlers”?它是上下文的一部分吗?抽象基类的一部分?

Simple State Diagram

感谢您的帮助!

+0

不清楚中断是否是最好的机制。如果你真的想直接被中断驱动,那么你应该中断一般的“泵”状态机动作。就我个人而言,当我做这样的事情时,我有一个中断处理程序将事件捕获到一个小队列中,然后在我有时间的情况下进行异步处理(这很快是人为的) - 它的工作原理与传统的PC键盘子系统非常相似并且实际上接受来自一个用于仿真的旋钮的输入)。 –

+0

@ChrisStratton概念上,我明白你在说什么。 NetMF也自动排队中断。我想让状态对一个旋转中断事件作出反应。中断可以执行并顺时针或逆时针“返回”。国家需要知道发生了什么,然后做出相应的反应。例如,State1正在监视一个传感器,然后出现旋转事件,它是顺时针的。状态一改变状态2.状态可以在循环中轮询一个标志,但它看起来效率低下。我也可以看到其他问题.. – GisMofx

+0

你真的需要这么做吗?是不是只是与状态枚举和切换下足够?你可以从那里重构它。 – Euphoric

回答

0

我做了一些更多的研究和这里的解决方案,我想出来的:

我用“状态”和“模式”互换

上下文类:

class ModeContext 
    { 
    private int rotationCount; 
    private string direction; 
    private State state; 
    public RotaryEncoder rotaryEncoderInstance; 


    public ModeContext(RotaryEncoder re) 
    { 
     this.State = new RPMMode(this); 
     rotaryEncoderInstance = re; 
     re.RotationEventHandler += OnRotationEvent;//attach to Context's Handler 
     rotationCount = 0; 
    } 

    public State State 
    { 
     get { return state; } 
     set { state = value; }//debug state change 
    } 

    //Event Handler   
    public void OnRotationEvent(uint data1, uint data2, DateTime time) 
    { 
     rotationCount++; 
     if (data1 == 1) 
     { 
      direction = "Clockwise"; 
      state.OnCWRotationEvent(this); 
     } 
     else 
     { 
      direction = "Counter-Clockwise"; 
      state.OnCCWRotationEvent(this); 
     } 
     Debug.Print(rotationCount.ToString() + ": " + direction + " Context Mode Rotation Event Fired!"); 
    } 

具体状态继承状态基类:

 class Mode2 : State 
     { 
     public override void Handle(ModeContext mode) 
     { 
      mode.State = new Mode2();//(mode); 
     } 

     public Mode2() 
     { 
      //do something; 
     } 
     #region event handlers 
     public override void OnCWRotationEvent(ModeContext mode) 
     { 
      mode.State = new Mode3(mode); 
     } 

     public override void OnCCWRotationEvent(ModeContext mode) 
     { 
      mode.State = new Mode1(mode); 
     } 
     #endregion 
    } 

现在我可以改变状态并给每个国家特定的控制行为,实际繁重的去哪里?

相关问题