命令模式:
Command:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
常用情况&&优点:
1, 较容易的设计一个命令列队
2, 较容易的将命令记入日志
3, 允许接收请求的一方决定是否否决请求
4, 支持可撤销的操作和重做
5, 加入新的具体命令类不影响其他类
6, 请求一个操作的对象与知道怎么执行一个操作的对象分割开
Demo1:
//抽象命令类
public abstract class Command
{
protected Barbecuer receiver;//烧烤者
public Command(Barbecuer receiver)
{
this.receiver = receiver;
}
abstract public void ExcuteCommand();//执行命令
}
//烧烤者,具体的实现类
public class Barbecuer
{
//烤羊肉,具体方法1
public void BakeMutton()
{
Console.WriteLine("烤羊肉。");
}
//烤鸡翅,具体方法2
public void BakeChickenWing()
{
Console.WriteLine("烤鸡翅。");
}
}
//具体命令类
//烤羊肉命令
class BakeMuttonCommand:Command
{
public BakeMuttonCommand(Barbecuer receiver) : base(receiver) { }
public override void ExcuteCommand()
{
receiver.BakeMutton();//调用虚方法里被传入的具体烧烤者执行具体方法
}
}
//烤鸡翅命令
class BakeChickenWingCommand : Command
{
public BakeChickenWingCommand(Barbecuer receiver)
: base(receiver )
{ }
public override void ExcuteCommand()
{
receiver.BakeChickenWing();
}
}
//服务员
public class Waiter
{
private IList<Command> order=new List<Command>();
//设置订单
public void SetOrder(Command command)
{
if (command.ToString() == "")
{
Console.WriteLine("鸡翅没了");
}
else
{
order.Add(command);
Console.WriteLine("增加订单"+command.ToString()+"时间"+DateTime.Now.ToString() );
}
}
//取消订单
public void CancelOrder(Command command)
{
order.Remove(command);
Console.WriteLine("取消订单" + command.ToString() + "时间" + DateTime.Now.ToString());
}
//通知执行
public void Notify()
{
foreach (Command c in order)
{
c.ExcuteCommand();
}
}
}
//开店前准备
Barbecuer boy = new Barbecuer();
Command bakeMuttonCommand1 = new BakeMuttonCommand(boy);
Command bakeMuttonCommand2 = new BakeMuttonCommand(boy);
Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy);
Waiter girl = new Waiter();
//开门营业
girl.SetOrder(bakeChickenWingCommand1 );
girl.SetOrder(bakeMuttonCommand1);
girl.SetOrder(bakeMuttonCommand2);
girl.CancelOrder(bakeChickenWingCommand1 );
//点菜完毕通知厨房
girl.Notify();
Console.ReadKey();