I'm using the command pattern to enable actions in my game to be undoable. ICommand defines individual commands, ICommandHandler does the undo-redo logic and might be decorated with other handlers like logging etc.
public interface ICommand
{
void Execute();
void Undo();
}
public interface ICommandHandler
{
void Execute(ICommand command);
void Undo();
void Redo();
}
public class CommandHandler : ICommandHandler
{
Stack<ICommand> _undoStack = new Stack<ICommand>();
Stack<ICommand> _redoStack = new Stack<ICommand>();
public void Execute(ICommand command)
{
if (command == null)
throw new ArgumentNullException("command");
command.Execute();
_undoStack.Push(command);
_redoStack.Clear();
}
public void Undo()
{
if (_undoStack.Count > 0)
{
ICommand undoCommand = _undoStack.Pop();
undoCommand.Undo();
_redoStack.Push(undoCommand);
}
}
public void Redo()
{
if (_redoStack.Count > 0)
{
ICommand redoCommand = _redoStack.Pop();
redoCommand.Execute();
_undoStack.Push(redoCommand);
}
}
}
So far I'm not having any problems. Please correct me if I'm doing anything horribly wrong, but my actual questions is: Can I safely use a struct as a concrete command object or should I use a class?
public struct MoveCameraCommand : ICommand
{
public CameraController cameraController;
public Vector2 moveDelta;
public MoveCameraCommand(CameraController controller, Vector2 moveDelta)
{
this.cameraController = controller;
this.moveDelta = moveDelta;
}
public void Execute()
{
cameraController.Move(moveDelta);
}
public void Undo()
{
cameraController.Move(-moveDelta);
}
}
I've noticed that when using a regular class, I'm generating garbage each frame with my camera, because move commands are issues very often. Since the game will be running on Android tablets, I was worried and switched to the struct implementation, although I've never seen it before. Might this cause other problems? Is this bad design in general? Should I not be using the command pattern for something like a camera, that is updated each frame?