using GFramework.Core.Abstractions.StateManagement;
namespace GFramework.Core.StateManagement;
///
/// Store 构建器的默认实现。
/// 该类型用于在 Store 创建之前集中配置比较器、reducer 和中间件,适合模块安装和测试工厂场景。
///
/// 状态树的根状态类型。
public sealed class StoreBuilder : IStoreBuilder
{
///
/// 延迟应用到 Store 的配置操作列表。
/// 采用延迟配置而不是直接缓存 reducer 适配器,可复用 Store 自身的注册和验证逻辑。
///
private readonly List>> _configurators = [];
///
/// action 匹配策略。
/// 默认使用精确类型匹配,只有在明确需要复用基类/接口 action 层次时才切换为多态匹配。
///
private StoreActionMatchingMode _actionMatchingMode = StoreActionMatchingMode.ExactTypeOnly;
///
/// 状态比较器。
///
private IEqualityComparer? _comparer;
///
/// 历史缓冲区容量。
/// 默认值为 0,表示不记录撤销/重做历史,以维持最轻量的运行时开销。
///
private int _historyCapacity;
///
/// 添加一个 Store 中间件。
///
/// 要添加的中间件。
/// 当前构建器实例。
public IStoreBuilder UseMiddleware(IStoreMiddleware middleware)
{
ArgumentNullException.ThrowIfNull(middleware);
_configurators.Add(store => store.UseMiddleware(middleware));
return this;
}
///
/// 基于给定初始状态创建一个新的 Store。
///
/// Store 的初始状态。
/// 已应用当前构建器配置的 Store 实例。
public IStore Build(TState initialState)
{
var store = new Store(initialState, _comparer, _historyCapacity, _actionMatchingMode);
foreach (var configurator in _configurators)
{
configurator(store);
}
return store;
}
///
/// 配置历史缓冲区容量。
///
/// 历史缓冲区容量;0 表示禁用历史记录。
/// 当前构建器实例。
/// 当 小于 0 时抛出。
public IStoreBuilder WithHistoryCapacity(int historyCapacity)
{
if (historyCapacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(historyCapacity), historyCapacity,
"History capacity cannot be negative.");
}
_historyCapacity = historyCapacity;
return this;
}
///
/// 配置 action 匹配策略。
///
/// 要使用的匹配策略。
/// 当前构建器实例。
public IStoreBuilder WithActionMatching(StoreActionMatchingMode actionMatchingMode)
{
_actionMatchingMode = actionMatchingMode;
return this;
}
///
/// 配置状态比较器。
///
/// 状态比较器。
/// 当前构建器实例。
public IStoreBuilder WithComparer(IEqualityComparer comparer)
{
_comparer = comparer ?? throw new ArgumentNullException(nameof(comparer));
return this;
}
///
/// 使用委托快速添加一个 reducer。
///
/// 当前 reducer 处理的 action 类型。
/// 执行归约的委托。
/// 当前构建器实例。
public IStoreBuilder AddReducer(Func reducer)
{
ArgumentNullException.ThrowIfNull(reducer);
_configurators.Add(store => store.RegisterReducer(reducer));
return this;
}
///
/// 添加一个强类型 reducer。
///
/// 当前 reducer 处理的 action 类型。
/// 要添加的 reducer。
/// 当前构建器实例。
public IStoreBuilder AddReducer(IReducer reducer)
{
ArgumentNullException.ThrowIfNull(reducer);
_configurators.Add(store => store.RegisterReducer(reducer));
return this;
}
}