using System; using System.Collections.Generic; using UnityEngine; namespace BaseGames.Core { /// /// 轻量服务定位器。通过类型键注册/查找服务,支持接口类型注册(依赖倒置)。 /// public static class ServiceLocator { private static readonly Dictionary _services = new(); /// 以接口类型 TInterface 注册实现 impl。 public static void Register(TInterface impl) => _services[typeof(TInterface)] = impl; /// 仅当尚未注册时才注册(防多场景重复注册同一服务)。 public static void RegisterIfAbsent(TInterface impl) { if (!_services.ContainsKey(typeof(TInterface))) _services[typeof(TInterface)] = impl; } /// 查找服务。未注册时抛出 InvalidOperationException。 public static TInterface Get() { if (_services.TryGetValue(typeof(TInterface), out var svc) && svc is TInterface typed) return typed; throw new InvalidOperationException( $"[ServiceLocator] Service '{typeof(TInterface).Name}' is not registered. " + "Ensure GameServiceRegistrar.Awake() has run before this call."); } /// 安全版 Get:未注册时返回 fallback,不报错(适用于可选服务)。 public static TInterface GetOrDefault(TInterface fallback = default) => _services.TryGetValue(typeof(TInterface), out var svc) && svc is TInterface typed ? typed : fallback; #if UNITY_EDITOR /// 单元测试中替换服务实现。 public static void OverrideForTest(TInterface mock) => _services[typeof(TInterface)] = mock; /// 清空所有注册(测试用)。 public static void Reset() => _services.Clear(); #endif } }