mardi 27 mars 2018

Strategy Pattern : Same group of function but takes different numbers of parameter

My post's title may not be the appropriate one anyway, I came across a design problem recently and though I think it's a very common but yet I'm not very sure how to solve it.

I have tow type of command sets.

Example for first type:

create_room 4

In the above command create_room is the command and 4 is the data on which the operation will be performed.

Example for second type:

exit

Which does not take any data to operate on.

My strategy is:

public interface ICommandExecutor
{
    stirng Execute (string command);
}
public class CreateRoom : ICommandExecutor
{
    public string Execute (string command)
    {
        //do the job
    }
}
public class Exit : ICommandExecutor
{
    public string Execute (string command)
    {
        //do the job
    }
}

Before that I have a factory to decide which version of implementation to be called based on command input.

ICommandExecutor executor = null;
if (command.Contains("exit"))
{
    executor = new Exit();
}
else if (command.Contains("create_room"))
{
    executor = new CreateRoom();
}

Now my problem here is with the implementation of the class Exit. The method public string Execute (string command) takes a parameter. Which is the command itself; in case if we have any data to operate on (like create_room 4). Command exit takes no data to operate on, so it is totally not necessary to pass the parameter. But my design forces me to pass it. What would be a better way to solve this problem.

Aucun commentaire:

Enregistrer un commentaire