refactor(state): 修改状态机接口返回类型支持链式调用

- 将Register方法返回类型从void改为IStateMachine
- 将Unregister方法返回类型从void改为IStateMachine
- 在实现类中添加return this语句
- 更新接口定义以匹配新的返回类型
- 实现链式调用功能提升API易用性
This commit is contained in:
GeWuYou 2026-01-17 13:20:33 +08:00
parent 9ae0f63324
commit ce6cb3f8df
2 changed files with 9 additions and 5 deletions

View File

@ -17,13 +17,13 @@ public interface IStateMachine
/// 注册一个状态到状态机中
/// </summary>
/// <param name="state">要注册的状态实例</param>
void Register(IState state);
IStateMachine Register(IState state);
/// <summary>
/// 从状态机中注销指定类型的状态
/// </summary>
/// <typeparam name="T">要注销的状态类型必须实现IState接口</typeparam>
void Unregister<T>() where T : IState;
IStateMachine Unregister<T>() where T : IState;
/// <summary>
/// 检查是否可以切换到指定类型的状态

View File

@ -24,24 +24,26 @@ public class StateMachine(int maxHistorySize = 10) : IStateMachine
/// 注册一个状态到状态机中
/// </summary>
/// <param name="state">要注册的状态实例</param>
public void Register(IState state)
public IStateMachine Register(IState state)
{
lock (_lock)
{
States[state.GetType()] = state;
}
return this;
}
/// <summary>
/// 从状态机中注销指定类型的状态
/// </summary>
/// <typeparam name="T">要注销的状态类型</typeparam>
public void Unregister<T>() where T : IState
public IStateMachine Unregister<T>() where T : IState
{
lock (_lock)
{
var type = typeof(T);
if (!States.TryGetValue(type, out var state)) return;
if (!States.TryGetValue(type, out var state)) return this;
// 如果当前状态是要注销的状态,则先执行退出逻辑
if (Current == state)
@ -60,6 +62,8 @@ public class StateMachine(int maxHistorySize = 10) : IStateMachine
States.Remove(type);
}
return this;
}
/// <summary>