一提到“命令”这个词,很多人首先都会想到的是军队。这就是命令:
王团长:“高连长!”
高连长:“到!”
王团长:“明天中午12点之前,派一个班到汶河南岸旧窑场阻击敌人,掩护大部队转移,免得被咬死,以集结号为令,随时准备撤退!”
高连长:“是!”
(画面切换)
高连长:“许三多!”
许三多:“到!”
高连长:“带领三班弟兄,明天中午12点之前,到汶河南岸旧窑场阻击敌人,掩护大部队转移,以集结号为令,随时准备撤退,只要听不见号声,你就是打剩下最后一个人,也得给我打下去!”
许三多:“报告,啥时候吹集结号?”
高连长:“少废话,给我上!”
许三多:“是!”
……
用程序设计的思维方式来思考这样的场景,我们就可以理解为:把命令封装为对象,使得发布者可以用不同的命令对接收者进行参数化。这样做的好处还有:可以记录命令日志,还可以撤销命令。
1: using System;
2:
3: namespace Autumoon.DesignPatterns.Command
4: {
5: public abstract class CommandDemo
6: {
7: public Soldier CurrentSoldier { get; set; }
8:
9: abstract public void Execute();
10: }
11:
12: public class ConcreteCommand : CommandDemo
13: {
14: override public void Execute()
15: {
16: Console.WriteLine("Command executed.");
17:
18: this.CurrentSoldier.InformAboutCommand();
19: }
20: }
21:
22: public class Soldier
23: {
24: public void InformAboutCommand()
25: {
26: Console.WriteLine("Soldier informed about command.");
27: }
28: }
29:
30: public class Officer
31: {
32: public CommandDemo TheCommand { get; set; }
33:
34: public void ExecuteCommand()
35: {
36: this.TheCommand.Execute();
37: }
38: }
39: }
那么我们来发布一个命令,过过指挥部队的瘾:
1: static void Main(string[] args)
2: {
3: #region Command
4: CommandDemo command = new ConcreteCommand();
5: command.CurrentSoldier = new Soldier();
6:
7: Officer officer = new Officer();
8: officer.TheCommand = command;
9: officer.ExecuteCommand();
10: #endregion
11:
12: Console.ReadLine();
13: }