我已经转向我的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"对于每个州?它是上下文的一部分吗?抽象基类的一部分?
感谢您的帮助!
答案 0 :(得分:0)
我做了更多研究,这是我提出的解决方案:
我使用" state"和"模式"可互换
上下文类:
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!");
}
继承State Base类的具体状态类:
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
}
既然我可以改变状态并给每个州特定的控制行为,那么实际的重举在哪里?