mardi 22 août 2017

How to implement a Hierarchical State Pattern

Im trying to implement a proper Hierarchical State Pattern (Dont know if implement is the right word for a pattern). Now as I understood from reading various articles, this type of State Machine has super states with sub states. So basically I need to organize all states as a hierarchy. The states higher in the hierarchy (super states) perform common tasks, while sub states inherit these commonalities and perform tasks which are more specific.

Now im not really sure how I should do this. Ive thought of something to try it out: We have a cat which can be alive or dead (not shown for the sake of simplicity). When alive the cat can sleep or stay awake. When its sleeping it can be either in a dreaming state or nightmare dreaming state.

What ive written so far but stuck with the design:

class Cat {
    public Dictionary<string, CatAlive> States = new Dictionary<string, CatAlive>();
    public CatAlive CurrentState;

    public Cat() {
        States.Add("Alive", new CatAlive());
        States.Add("Awake", new CatAwake());
        States.Add("Sleeping", new CatSleeping());
        // And so on

        CurrentState = States["Alive"];
    }

    public void ChangeState(string state) {
        CurrentState.Exit(this);
        CurrentState = States[state];
        CurrentState.Enter(this);
    }
}

interface IState {
    void Enter(Cat cat);
    void Exit(Cat cat);
}

class CatAlive : IState {
    public virtual void Enter(Cat cat) {

    }

    public void WakeUp(Cat cat) {
        cat.ChangeState("CatAwake");
    }

    public void Sleep() {

    }

    public virtual void Exit(Cat cat) {

    }
}

class CatAwake : CatAlive, IState {
    public override void Enter(Cat cat) {

    }

    public override void Exit(Cat cat) {

    }
}

class CatSleeping : CatAlive, IState {
    public override void Enter(Cat cat) {

    }

    public override void Exit(Cat cat) {

    }
}

class CatDayDreaming : CatAlive, IState {
    public override void Enter(Cat cat) {

    }

    public override void Exit(Cat cat) {

    }
}

class CatNightDreaming : CatAlive, IState {
    public override void Enter(Cat cat) {

    }

    public override void Exit(Cat cat) {

    }
}

My question is, am I on the right track? What can be improved?

Aucun commentaire:

Enregistrer un commentaire