参数化
参数化是在命令模式的定义中出现的:
- 将请求封装成对象,让你可以将客户端的不同请求参数化,并配合队列、记录、复原等方法来执行请求操作。
定义中说到,我们可以将命令模式参数化,其实就是在命令对象构造时传参。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public interface ICommand { void Execute(); } public class AttackHeroCommand { private int mHP; public AttackHeroCommand(int hp) { mHP = hp; } public void Execute() { var heroModel = HeroModel.Get(); heroModel.HP -= mHP; MsgSender.Send("UPDATE_HP",heroModel.HP); } } void Start() { var attackHeroCommand = new AttackHeroCommand(10); attackHeroCommand.Execute(); var attackHeroCommand2 = new AttackHeroCommand(20); attackHeroCommand2.Execute(); }
|
撤销
我们再看一下命令模式的定义
- 将请求封装成对象,让你可以将客户端的不同请求参数化,并配合队列、记录、复原等方法来执行请求操作。
定义中的“记录、复原”操作就是这里我们讲的撤销。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public interface IUndoableCommand { void Execute(); void Undo(); }
public class MoveForwardCommand : IUndoableCommand { public void Execute() { var player = GameObject.Find("Player").transform; player.position += Vector3.forward; } public void Undo() { var player = GameObject.Find("Player").transform; player.position -= Vector3.forward; } }
void Start() { var commands = new List<IUndoableCommand>() { new MoveForwardCommand(), new MoveForwardCommand() } commands.ForEach(c => c.Execute()); for(int i = commands.Count - 1;i >= 0; i--) { commands[i].Undo(); } }
|
一般情况下,如果需要支持撤销,我们需要把每个可撤销的命令缓存到List或者Stack中