Voglio trovare più elegante e apprezzare il modo di iniettare processori in CommandProcessorDispatcher
class. Oppure può essere un'altra soluzione (l'obiettivo è separare ogni logica di elaborazione dei comandi alla classe indipendente). Forse qualche schema di progettazione può essere utile qui. Grazie.
public interface ICommand { }
public class StartCommand : ICommand { }
public class StopCommand : ICommand { }
public interface ICommandProcessor<in T> where T : ICommand
{
void Process(T command);
}
public class StartCommandProcessor : ICommandProcessor<StartCommand>
{
public void Process(StartCommand command) { }
}
public class StopCommandProcessor : ICommandProcessor<StopCommand>
{
public void Process(StopCommand command) { }
}
public interface ICommandProcessorDispatcher
{
void Process(ICommand command);
}
public class CommandProcessorDispatcher : ICommandProcessorDispatcher
{
public CommandProcessorDispatcher(Dictionary<Type, Action<ICommand>> processors)
{
_processors = processors;
}
private readonly Dictionary<Type, Action<ICommand>> _processors;
public void Process(ICommand command)
{
_processors[command.GetType()](command);
}
}
internal class Program
{
private static void Main(string[] args)
{
var dict = new Dictionary<Type, Action<ICommand>>
{
{ typeof(StartCommand), x => new StartCommandProcessor().Process((StartCommand)x) },
{ typeof(StopCommand), x => new StopCommandProcessor().Process((StopCommand)x) },
};
var dispatcher= new CommandProcessorDispatcher(dict);
}
}