// --------------------------------------------------------------------------------------------- // Copyright (c) 2021-2025, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // --------------------------------------------------------------------------------------------- namespace Pal3.Game.Command { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Core.Command; /// /// A generic class that dispatches commands to their registered executors. /// /// The type of command to dispatch. public sealed class CommandDispatcher { private readonly ICommandExecutorRegistry _commandExecutorRegistry; private readonly Dictionary _commandExecutorExecuteMethodInfoCache = new(); private CommandDispatcher() { } public CommandDispatcher(ICommandExecutorRegistry commandExecutorRegistry) { _commandExecutorRegistry = commandExecutorRegistry; } /// /// Route a command to the registered executor(s) in the registry and execute the command. /// public bool TryDispatchAndExecute(T command) where T : TCommand { // Call ToList to prevent modified collection exception since a new executor may be registered during the iteration. IList> executors = _commandExecutorRegistry.GetRegisteredExecutors().ToList(); if (!executors.Any()) return false; foreach (ICommandExecutor executor in executors) { executor.Execute(command); } return true; } /// /// Route a command to the registered executor(s) in the registry and execute the command. /// public bool TryDispatchAndExecute(TCommand command) { Type commandExecutorType = typeof(ICommandExecutor<>).MakeGenericType(command.GetType()); // Call ToList to prevent modified collection exception since a new executor may be registered during the iteration. IList executors = _commandExecutorRegistry.GetRegisteredExecutors(commandExecutorType).ToList(); if (!executors.Any()) return false; foreach (object executor in executors) { if (GetCommandExecutorExecuteMethod(commandExecutorType) is { } method) { method.Invoke(executor, new object[] {command}); } } return true; } private MethodInfo GetCommandExecutorExecuteMethod(Type commandExecutorType) { if (_commandExecutorExecuteMethodInfoCache.TryGetValue(commandExecutorType, out MethodInfo executeMethod)) { return executeMethod; } if (commandExecutorType.GetMethod(nameof(ICommandExecutor.Execute)) is { } method) { _commandExecutorExecuteMethodInfoCache[commandExecutorType] = method; return method; } return null; } } }