supervisor-simulator/scripts/Core/EventBus.cs
2026-01-11 23:57:24 +08:00

72 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
namespace Core;
/// <summary>
/// 轻量事件总线(解耦系统之间的通信)
/// 设计说明:
/// 1) 系统层发布 DomainEventView/Controller 可订阅。
/// 2) 不依赖 Godot Signal便于纯逻辑测试。
/// 注意事项:
/// - 事件为进程内同步调用,避免在事件里做耗时操作。
/// 未来扩展:
/// - 可加入“事件队列”和“延迟派发”以支持回合结算。
/// </summary>
public sealed class DomainEventBus
{
private readonly Dictionary<Type, List<Delegate>> _handlers = new();
/// <summary>
/// 订阅事件
/// </summary>
/// <typeparam name="T">事件类型</typeparam>
/// <param name="handler">事件处理器</param>
public void Subscribe<T>(Action<T> handler)
{
var type = typeof(T);
if (!_handlers.TryGetValue(type, out var list))
{
list = new List<Delegate>();
_handlers[type] = list;
}
list.Add(handler);
}
/// <summary>
/// 取消订阅事件
/// </summary>
/// <typeparam name="T">事件类型</typeparam>
/// <param name="handler">事件处理器</param>
public void Unsubscribe<T>(Action<T> handler)
{
var type = typeof(T);
if (_handlers.TryGetValue(type, out var list))
{
list.Remove(handler);
}
}
/// <summary>
/// 发布事件
/// </summary>
/// <typeparam name="T">事件类型</typeparam>
/// <param name="evt">事件对象</param>
public void Publish<T>(T evt)
{
var type = typeof(T);
if (!_handlers.TryGetValue(type, out var list))
{
return;
}
foreach (var handler in list)
{
if (handler is Action<T> typedHandler)
{
typedHandler.Invoke(evt);
}
}
}
}