Sunday, November 18, 2007

Command Pattern

hi,
we will discuss about command pattern today !!!

scenario :
i am developing a game where i have my main character running,sitting and standing.
for now , will print "sit" when he sits,"stand" when he stands,"run" when he runs.
how do we go about this?
simple solution which falshes on to our mind right now is
1)develop and enum haveing its members as run,sit and stand.
2) in the user class,have this enum.
3) when any command is performed on the user handle it in a function called ExecuteCommand. In this function have an if loop and check for the enum.

voila, we get the output !!!!
so where is the problem?
well, my character is still evolving in the game. so now i identify a new scenario where the character has to sleep.so, i have to modify the user class by adding a new new enum "sleep" and then modify the if condition.....dont you think this is bad????
tomorrow i can identify some new user actions, then again i have to modify this?
naaah..this will not do...
how can we do a proper design for this?
this is where we use the command pattern.
in this pattern we make each and every user action as a class.and this class will handle its own command and perform the action necessary.
i mean " encapsulate a command into an object".

see the example below

public interface ICommand
{
void Execute();
}

public class RunCommand : ICommand
{
#region ICommand Members

public void Execute()
{
Console.WriteLine("Run Command executed");
}

#endregion

}

public class StandCommand : ICommand
{
#region ICommand Members

public void Execute()
{
Console.WriteLine("Stand Command executed");
}

#endregion

}

public class User
{
public void Action(ICommand cmd)
{
cmd.Execute();
}
}

and when i call this:

User Character = new User();
ICommand cmd = new RunCommand();
Character.Action(cmd);

so i create an instance of the command needed and pass it on to the Action function.
and then the class (command class) performs the necessary action.

now of i want to add a new command - sleep?
all i need to do is create a new class called Sleep,implement ICommand.
then implement the function Execute.
a new action has been introduced.
not if i want the user ot perfrom this :

ICommand SleepCmd = new SleepCommand();
Character.Action(SleepCmd);

this will perform the necessary action.

HAPPY CODING!!!!

regards,
nandan

No comments: