标签:void private abstract static 参数化 can move wait write
命令模式(Command),将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化:对请求排队或记录请求日志,以及支持可撤销的操作。
1 //烤肉者
2 public class Barbecuer
3 {
4 public void BakeMutton()
5 {
6 Console.WriteLine("烤羊肉串");
7 }
8 public void BakeChickenWing()
9 {
10 Console.WriteLine("烤鸡翅");
11 }
12 }
1 //抽象命令
2 public abstract class Command
3 {
4 protected Barbecuer receiver;
5 //确定烤肉串者
6 public Command(Barbecuer receiver)
7 {
8 this.receiver = receiver;
9 }
10
11 public abstract void ExcuteCommand();
12 }
1 //烤羊肉串命令
2 public class BakeMuttonCommand : Command
3 {
4 public BakeMuttonCommand(Barbecuer receiver) : base(receiver)
5 {
6 }
7
8 public override void ExcuteCommand()
9 {
10 receiver.BakeMutton();
11 }
12 }
1 //烤鸡翅串命令
2 public class BakeChickenWingCommand : Command
3 {
4 public BakeChickenWingCommand(Barbecuer receiver) : base(receiver)
5 {
6 }
7
8 public override void ExcuteCommand()
9 {
10 receiver.BakeChickenWing();
11 }
12 }
//服务员类,不管用户想要什么烤肉,反正都是‘命令’,只管记录订单,
//然后通知‘烤肉者’执行即可
public class Waiter
{
private List<Command> orders = new List<Command>();
//设置订单
public void SetOrader(Command command)
{
if (command.ToString() == "_18.命令模式.BakeChickenWingCommand")
{
Console.WriteLine("服务员:鸡翅没有了,请点别的烧烤");
}
else
{
orders.Add(command);
Console.WriteLine("增加订单:" + command.ToString() +
" 时间:" + DateTime.Now.ToString());
}
}
//取消订单
public void CancelOrder(Command command)
{
orders.Remove(command);
Console.WriteLine("取消订单:" + command.ToString() +
" 时间:" + DateTime.Now.ToString());
}
//通知执行
public void Notify()
{
foreach (var i in orders)
{
i.ExcuteCommand();
}
}
}
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Barbecuer bb = new Barbecuer();
6 Command c1 = new BakeMuttonCommand(bb);
7 Command c3 = new BakeMuttonCommand(bb);
8 Command c2 = new BakeChickenWingCommand(bb);
9 Waiter gg = new Waiter();
10
11 gg.SetOrader(c1);
12 gg.SetOrader(c2);
13 gg.SetOrader(c3);
14
15 //订单完毕,通知厨房
16 gg.Notify();
17 Console.WriteLine("-----------------------");
18 gg.CancelOrder(c3);
19 gg.Notify();
20
21
22 Console.ReadKey();
23
24 }
25 }
1、他能较容易地设计一个命令队列
2、在需要的情况下,可以较容易地将命令记入日志
3、允许接收请求的一方决定是否取消请求
4、可以容易地实现对请求的撤销和重做
5、由于加进新的具体命令类不影响其他的类,因此增加新的额具体命令类很容易
6、命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分隔开。
标签:void private abstract static 参数化 can move wait write
原文地址:https://www.cnblogs.com/hyunbar/p/9982127.html