阶段的适当数据结构 - 枚举?

时间:2013-02-07 18:21:45

标签: c# asp.net-mvc-3 database-design asp.net-mvc-4

我有两个类:抽认卡和套装。抽认卡属于七个阶段之一 - 每个阶段都应具有TimeSpan属性。目标是在特定时间段后显示牌,具体取决于牌所在的舞台。

一组也属于这七个阶段之一 - 所有牌中的最低阶段。

这两个类目前都有一个“public int Stage”属性,但我觉得这不太理想。

根据类/对象定义,对此进行建模的适当方法是什么?我正在使用MVC4 EF CodeFirst,以防万一。

1 个答案:

答案 0 :(得分:0)

状态机:http://en.wikipedia.org/wiki/State_pattern

基本上,你有一个状态环(所有状态都实现一个接口)。然后你让你的状态移位器类实现一个'参与者'接口,如下所示:

// All stages should implement this
interface IStateRing
{

}

// Everything participating in the state ring should implement this
interface IStateRingParticipant
{
    void SetStage(IStateRing stage);
}

您的参与者班级唯一的工作就是在状态告诉时响应状态的变化,如下所示:

class MyStageParticipant : IStateRingParticipant
{
    // Keep track of the current state.
    IStateRing currentStage;

    // This is called by the state when it's time to change
    public void SetStage(IStateRing stage)
    {
        throw new NotImplementedException();
    }
}

注意它会跟踪它所处的状态,然后有一个由当前状态调用的函数SetStage。接下来我们有各州:

// The state handles the actual functionality, and when it's good and ready
// it commands the participant to change states.
class StateA : IStateRing
{
    // Keep track of the participant.
    IStateRingParticipant participant;

    // The constructor should know what object belongs to this state.
    // that is, which object is participating.
    public StateA(IStateRingParticipant participant)
    {
        this.participant = participant;
    }

    // We do all of our processing in this state.
    // Then when it's time we simply let go of the participant and 
    // instantiate a new state.
    public void GoodAndReady()
    {
        new StateB(participant);
    }
}

class StateB : IStateRing
{
    IStateRingParticipant participant;

    public StateB(IStateRingParticipant participant)
    {
        this.participant = participant;
    }
}

请注意,构造函数的一部分是接受参与者。状态管理所有实际处理,然后当它好并准备好时,它实例化下一个状态(也保持当前状态),依此类推。

使用状态模式,将所有功能路由到状态,然后让他们弄清楚何时应该更改状态(通过实例化状态的新实例)。