Well basically, I have an Engine class that recieves a command as string from the input and passes it to a CommandHandler class which executes the apropriate command.
The CommandHandler passes the string to a CommandFactory to get the command and calls the method Execute() of the command, but the problem is that every command depends on different classes to execute properly. For example, one commands need the IOutputWriter to write something, the other needs IBuldingFactory to create a building, etc. I am using a reflection in the CommandFactory class, and I can't pass the dependencies through the constructor using Activator.CreateInstance(), because every command has different dependencies.
My current architecture looks something like this:
class Engine()
{
IData data; // application database
IInputReader inputReader;
ICommandHandler commandHandler;
public void Run()
{
string command = inputReader.Read();
commandHandler.Handle(command, data);
}
}
class CommandHandler()
{
ICommandFactory commandFactory();
public void Handle(string command, IData data)
{
string executableCommand = commandFactory().createCommand(command);
executableCommand.Execute(data);
}
}
class DisplayDataCommand : ICommand
{
IOutputWriter outputWriter;
public void Execute(IData data)
{
outputWriter.Print(data.ToString());
}
}
class BuildCommand : ICommand
{
IBuildingFactory buildingFactory;
string buildingType;
public void Execute(IData data)
{
var building = buildingFactory.createBuilding(buildingType);
data.AddBuilding(building);
}
}
I can have different methods in the command handler for each command and call the appropriate method using switch case, but that would violate the Open/Closed principle. So my real question is - How to implement this without violating the Open/Closed principle.
Factory
. I would recommend looking up "Inversion of Control Containers". They should be able to get you started on what you are looking for. We use Autofac where I work, and it has worked well for us.