gpt4 book ai didi

c - 有没有典型的状态机实现模式?

转载 作者:太空狗 更新时间:2023-10-29 16:14:41 26 4
gpt4 key购买 nike

我们需要用C实现一个简单的状态机。
标准的 switch 语句是最好的方法吗?
我们有一个当前状态(state)和一个转换触发器。


switch(state)
{
case STATE_1:
state = DoState1(transition);
break;
case STATE_2:
state = DoState2(transition);
break;
}
...
DoState2(int transition)
{
// Do State Work
...
if(transition == FROM_STATE_2) {
// New state when doing STATE 2 -> STATE 2
}
if(transition == FROM_STATE_1) {
// New State when moving STATE 1 -> STATE 2
}
return new_state;
}

简单状态机有没有更好的方法

编辑: 对于 C++,我认为 Boost Statechart图书馆可能是要走的路。但是,它对 C 语言没有帮助。让我们专注于 C 用例。

最佳答案

对于大多数状态机,我更喜欢使用表驱动的方法:

typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;
typedef struct instance_data instance_data_t;
typedef state_t state_func_t( instance_data_t *data );

state_t do_state_initial( instance_data_t *data );
state_t do_state_foo( instance_data_t *data );
state_t do_state_bar( instance_data_t *data );

state_func_t* const state_table[ NUM_STATES ] = {
do_state_initial, do_state_foo, do_state_bar
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
return state_table[ cur_state ]( data );
};

int main( void ) {
state_t cur_state = STATE_INITIAL;
instance_data_t data;

while ( 1 ) {
cur_state = run_state( cur_state, &data );

// do other program logic, run other state machines, etc
}
}

这当然可以扩展为支持多个状态机等。也可以容纳转换 Action :

typedef void transition_func_t( instance_data_t *data );

void do_initial_to_foo( instance_data_t *data );
void do_foo_to_bar( instance_data_t *data );
void do_bar_to_initial( instance_data_t *data );
void do_bar_to_foo( instance_data_t *data );
void do_bar_to_bar( instance_data_t *data );

transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = {
{ NULL, do_initial_to_foo, NULL },
{ NULL, NULL, do_foo_to_bar },
{ do_bar_to_initial, do_bar_to_foo, do_bar_to_bar }
};

state_t run_state( state_t cur_state, instance_data_t *data ) {
state_t new_state = state_table[ cur_state ]( data );
transition_func_t *transition =
transition_table[ cur_state ][ new_state ];

if ( transition ) {
transition( data );
}

return new_state;
};

表驱动方法更易于维护和扩展,并且更易于映射到状态图。

关于c - 有没有典型的状态机实现模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/133214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com