mercredi 14 décembre 2016

Design pattern - Client Server - Command pattern

I have a bunch of commands that I need to batch from the client and execute at the server. These commands are of different types and the contract for the command and the corresponding return types is shared between the client and server via a library.

Client side code is as follows-

var client = new ClientSDK();
client.Add(new Command1());
client.Add(new Command2());
client.Add(new Command3());

// Execute transmits all the commands to the server 
var results = client.Execute();

Server code -

List<CommandResult> Execute(List<CommandBase> commands)
{
   List<CommandResult>  results = new List<CommandResult>();
   foreach(CommandBase command in commands)
   {
       if(command.GetType == Command1)
       {
           results.Add(new Command1Executor(command).Execute())
       }
       else if(command.GetType == Command2)
       {
           results.Add(new Command1Executor(command).Execute())
       }
       else if(command.GetType == Command3)
       {
           results.Add(new Command3Executor(command).Execute())
       }    
       ..................     
   }
}

For each command there exists a unique execute function, that cannot be exposed as part of the client SDK. How do I make design changes such that I can get rid of the massive if/else block? There are tons of commands to be supported. I tried applying the command pattern as suggested here - using the command and factory design patterns for executing queued jobs but this requires each command to implement the ICommand interface, which is not possible

Is there a better way to design this?

Aucun commentaire:

Enregistrer un commentaire