64 lines
987 B
C#
64 lines
987 B
C#
|
|
|
|
using System;
|
|
|
|
|
|
|
|
namespace imm;
|
|
|
|
|
|
|
|
public record class Context : imm.Recorded<Context>
|
|
{
|
|
|
|
}
|
|
|
|
public record class State<T, CTX> : imm.Recorded<State<T, CTX>>
|
|
where T : State<T, CTX>
|
|
where CTX : Context
|
|
{
|
|
virtual public (CTX, T) onEnter(CTX ctx, State<T, CTX> oldState)
|
|
{
|
|
return (ctx, (T)this);
|
|
}
|
|
|
|
virtual public (CTX, T) onExit(CTX ctx, State<T, CTX> newState)
|
|
{
|
|
return (ctx, (T)this);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public record class FSM<T, CTX, ST> : imm.Recorded<FSM<T, CTX, ST>>
|
|
where T : FSM<T, CTX, ST>
|
|
where CTX : Context
|
|
where ST : State<ST, CTX>
|
|
{
|
|
public CTX Context { get; private set; }
|
|
public ST State { get; private set; }
|
|
|
|
public FSM( CTX context, ST stStart )
|
|
{
|
|
Context = context;
|
|
State = stStart;
|
|
}
|
|
|
|
public FSM<T, CTX, ST> Transition(ST newState)
|
|
{
|
|
var (newOldCTX, oldState) = State.onExit(Context, newState);
|
|
|
|
var (newCTX, storeState) = newState.onEnter(newOldCTX, oldState);
|
|
|
|
return this with
|
|
{
|
|
Context = newCTX,
|
|
State = storeState,
|
|
};
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|