State machine in CTRL++

Find and share HowTos to various installations / configurations!
2 posts • Page 1 of 1
willw
Posts:22
Joined: Thu Nov 19, 2015 4:40 pm

State machine in CTRL++

Post by willw »

I would like to implement the GoF State Machine pattern in CTRL++, but after a bit of playing around, I conclude that it is impossible.

The pattern https://en.wikipedia.org/wiki/State_pattern requires two classes:
  • The context class, which handles events and takes actions, and
  • The state class, an instance of which is owned by the context. The state class has an abstract base, and is derived for each actual state.
The problem is that the context class needs to know about the state class, since it owns an instance of it to represent its current state. But the state class also needs to know about the context class, since it needs to be able to call methods on it in response to events.

Since CTRL++ requires a class to be fully declared before it can be referenced, this cannot be implemented, as far as I can see.

Even 'cheating' mechanisms, such as having the State class's methods return the string name of a static function in the context class fail to work:

Code: Select all

// Example concrete state class
class Damper_Closing_State: Damper_Base_State
{
    public string onOpenCmd()   {  return "startOpening";  }
    // ...
};


class Damper_Context
{
    shared_ptr<Damper_Base_State> _state;  // Contains shared_ptr instance of concrete state class

    private call(string methodName) {
           // ************************ Attempt to call a static function fails to resolve!
            callFunction("Damper_Context::" + methodName, this);
    }

    public static void startOpening(Damper_Context self) {
        
    }
}
Is there any workaround for this?

gschijndel
Posts:376
Joined: Tue Jan 15, 2019 3:12 pm

Re: State machine in CTRL++

Post by gschijndel »

What are you trying to accomplish with the state machine pattern?
Instead of calling a context function to set the next state handler, you could return it.

Is it an option to implement a strategy pattern instead of the state pattern?

2 posts • Page 1 of 1