命令模式(Command)
定义
命令模式(Command),将一个请求封闭为一个对象,从而使你可以用不同的请求对客户进行参数化;对请求排除或记录请求日志,以及支持可撤销的操作。
类图
描述
Command:定义命令的统一接口;
ConcreteCommand:Command接口的实现者,要执行的具体命令;
Receiver:命令的实际执行者;
Invoker:命令的请求者,是命令模式中最重要的角色,用来对各个命令进行控制。
应用场景
顾客在餐馆用餐的时候,首先由顾客点餐,服务员记录顾客的点餐情况,然后服务员把订单传到后厨,厨师根据订单把顾客点的餐烹饪好。
/// <summary> /// 厨师 /// </summary> public class Chef { public void CookBeef() { Console.WriteLine("大厨开始爆炒牛肉."); Console.WriteLine("爆炒牛肉出锅."); } public void CookFish() { Console.WriteLine("大厨开始水煮鱼."); Console.WriteLine("水煮鱼出锅."); } public void CookEggplant() { Console.WriteLine("大厨开始红烧茄子."); Console.WriteLine("红烧茄子出锅."); } } public abstract class Command { public string Name { get; set; } public abstract void Cook(); } /// <summary> /// 爆炒牛肉 /// </summary> public class CookBeefCommand : Command { private Chef chef; public CookBeefCommand(Chef chef) { this.chef = chef; base.Name = "爆炒牛肉"; } public override void Cook() { this.chef.CookBeef(); } } /// <summary> /// 红烧茄子 /// </summary> public class CookEggplantCommand : Command { private Chef chef; public CookEggplantCommand(Chef chef) { this.chef = chef; base.Name = "红烧茄子"; } public override void Cook() { this.chef.CookEggplant(); } } /// <summary> /// 水煮鱼 /// </summary> public class CookFishCommand : Command { private Chef chef; public CookFishCommand(Chef chef) { this.chef = chef; base.Name = "水煮鱼"; } public override void Cook() { this.chef.CookFish(); } } /// <summary> /// 服务员 /// </summary> public class Waiter { private List<Command> commands; public Waiter() { this.commands = new List<Command>(); } public void SetOrder(Command command) { this.commands.Add(command); Console.WriteLine("增加订单:" + command.Name); } public void CancelOrder(Command command) { this.commands.Remove(command); Console.WriteLine("取消订单:" + command.Name); } public void Notify() { foreach (Command command in this.commands) { command.Cook(); } } }