c语言 状态机,c – 状态机实现

我有一个如下所述的状态机.

我们可以从两种起始状态中的一种开始,但我们必须触及握手的所有4种状态.从那里,我们可以传输数据的有效载荷或接收数据的有效载荷.然后,我们回到原来的起始状态.

握手:

– > StartingState1 – > FinalState1 – > StartingState2 – > FinalState2

– > StartingState2 – > FinalState2 – > StartingState1 – > FinalState1

有效负载转移:

– > SendPayload – > SendEnd – > StartingState?

– > ReceivePayload – > ReceiveEnd – > StartingState?

下面的代码代表了我当前的架构.不幸的是,在每个过程结束时,我没有从州内获得足够的信息来了解我应该触及的下一个状态.

有没有人对如何根据我的要求改进这种架构有任何建议?

谢谢,

PaulH

class MyMachine;

class Payload;

class IState

{

MyMachine* context_;

IState( MyMachine* context ) : context_( context) {};

virtual void Consume( byte data );

void ChangeState( IState* state )

{

context_->SetState( state );

}

}

class FinalState1 : IState

{

void Consume( byte data )

{

// Either go to StartingState1,SendPayload,or ReceivePayload.

// How can I tell from within the context of this state where I

// should go?

}

}

class StartingState1 : IState

{

void Consume( byte data )

{

if ( /*some condition*/ )

{

ChangeState( new FinalState1( context_ ) );

}

}

}

class MyMachine

{

IState* state_;

Payload* payload_;

void Start1( Mode mode )

{

state_ = new StartingState1( this );

}

void Start2( Mode mode )

{

state_ = new StartingState2( this );

}

void Consume( byte data )

{

state_->Consume( data );

}

void SetPayload( const Payload* payload )

{

payload_ = payload;

}

const Payload* GetPayload()

{

return payload_;

}

void SetState( State* state )

{

delete state_;

state_ = state;

}

}

// get a byte of data from some source

byte GetData();

void main()

{

MyMachine machine;

Payload payload;

machine.SetPayload( payload );

machine.Start1( Mode::SendPayload );

// could also call:

// machine.Start1( Mode::ReceivePayload );

// machine.Start2( Mode::SendPayload );

// machine.Start2( Mode::ReceivePayload );

for(;;)

{

machine.Consume( GetData() );

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值