命令模式 -- 大话设计模式
在今天,读书有时是件“麻烦”事。它需要你付出时间,付出精力,还要付出一份心境。--仅以《大话设计模式》来祭奠那逝去的……
命令模式:将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销操作
1.烧烤店就餐
烧烤男孩和服务员女孩,开门营业,客户点餐,女孩记单,客人点完菜,女孩通知男孩开做
定义烧烤师傅类
/// <summary> /// 烤肉串师傅类 /// </summary> public class Barbecuer { public void BakeMutton() { Console.WriteLine("烤羊肉串"); } public void BakeChickenWing() { Console.WriteLine("烤鸡翅"); } }
定义抽象命令类和具体命令类
/// <summary> /// 抽象命令 /// </summary> public abstract class Command { protected Barbecuer receiver; public Command(Barbecuer receiver) { this.receiver = receiver; } public abstract void ExcuteCommand(); } /// <summary> /// 烤肉命令 /// </summary> public class BakeMuttonCommand : Command { public BakeMuttonCommand(Barbecuer receiver) : base(receiver) { } public override void ExcuteCommand() { receiver.BakeMutton(); } } /// <summary> /// 烤肉命令 /// </summary> public class BakeChickenWingCommand : Command { public BakeChickenWingCommand(Barbecuer receiver) : base(receiver) { } public override void ExcuteCommand() { receiver.BakeChickenWing(); } }
定义服务员类
/// <summary> /// 服务员 /// </summary> public class Waiter { private IList<Command> orders = new List<Command>(); /// <summary> /// 设置订单 /// </summary> public void SetOrder(Command command) { orders.Add(command); Console.WriteLine("增加订单:{0};时间:{1}", command.ToString(), DateTime.Now); } /// <summary> /// 取消订单 /// </summary> public void CancleOrder(Command command) { orders.Remove(command); Console.WriteLine("取消订单:{0};时间:{1}", command.ToString(), DateTime.Now); } /// <summary> /// 全部通知 /// </summary> public void Notify() { foreach (var v in orders) { v.ExcuteCommand(); } } }
开启场景模拟
static void Main(string[] args) { //烧烤男孩和服务员女孩 Barbecuer boy = new Barbecuer(); Waiter girl = new Waiter(); //开门营业,客户点餐,女孩记单 girl.SetOrder(new BakeMuttonCommand(boy)); girl.SetOrder(new BakeChickenWingCommand(boy)); //客人点完菜,女孩通知男孩开做 girl.Notify(); }