***本文与作者原文有一定的偏差,其中加入了一部分是个人看法,详细请查看作者原文。***
原文连接http://www.dofactory.com/Patterns/PatternCommand.aspx
命令模式意图:
GOF 在《设计模式》一书中阐述其意图:“将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。”这里所谓的“不同的请求”也既意味着请求可能发生的变化,是一个可能扩展的功能点。
命令模式UML图:

Command模式将一个请求封装为一个对象,从而使你可以使用不同的请求对客户进行参数化。
简单示例:
1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace DesignPattern.Command6


{7
class Program8

{9
static void Main(string[] args)10

{11
// 创建receiver、command和invoker 12
Receiver receiver = new Receiver();13

14
//根据多态,父类的引用指向子类对象15
Command command = new ConcreteCommand(receiver);16
Invoker invoker = new Invoker();17

18
//设置和执行命令19
invoker.SetCommand(command);20
invoker.ExecuteCommand();21

22
Console.Read();23
}24
}25
}26

1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace DesignPattern.Command6


{7
public abstract class Command8

{9
protected Receiver receiver;10

11

/**//// <summary>12
/// 构造器注入13
/// </summary>14
/// <param name="receiver"></param>15
public Command(Receiver receiver)16

{17
this.receiver = receiver;18
}19

20
public abstract void Execute();21
}22
}23

1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace DesignPattern.Command6


{7
public class Invoker8

{9
private Command command;10

11
public void SetCommand(Command command)12

{13
this.command = command;14
}15

16
public void ExecuteCommand()17

{18
command.Execute();19
}20
}21
}22

1
using System;2
using System.Collections.Generic;3
using System.Text;4

5
namespace DesignPattern.Command6


{7
public class Receiver8

{9
public void Action()10

{11
Console.WriteLine("Called Receiver.Action()");12
}13
}14
}15

运行结果:
在众多的设计模式中,Command模式是很简单也很优雅的一种设计模式。Command模式它封装的是命令,把命令发出者的责任和命令执行者的责任分开。[TerryLee]
注意:
如果比较类图结构,我门会发现Command模式、Strategy模式、State模式是完全一样的。事实正是如此,由于他门的设计思想都是对易于变化的部分进行抽象、或为接口。唯一的区别,就是所抽象的行为职责不同而已,这一点从各自的名字就可以看出。
参考资料:
TerryLee------.NET设计模式系列
Bruce Zhang---《软件设计精要与模式》
www.dofactory.com
本文示例源码下载