I want find more elegant and appreciate way to inject processors into CommandProcessorDispatcher
class. Or it can be another one solution (the goal is separate each command processing logic to independent class). Maybe some design pattern can be useful here. Thank you.
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);
}
}