首页 > 代码库 > 设计模式--命令模式

设计模式--命令模式

将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
作用:
1、它能较容易地设计一个命令队列;
2、在需要的情况下,可以较容易地将命令记入日志;
3、允许接收请求的一方决定是否要否决请求;
4、可以容易地实现对请求的撤销和重做;
5、由于加进新的具体命令类不影响其他的类,因此增加新的具体命令类很容易。

 

//基本

//知道如何实施与执行一个与请求相关的操作,任何类都可能作为一个接收者。
class Receiver
{
public void Action()
{
Console.WriteLine("执行请求!");
}
public void Action1()
{
Console.WriteLine("执行请求2!");
}
}

//声明执行操作的接口
abstract class Command
{
protected Receiver receiver;

public Command(Receiver receiver)
{
this.receiver = receiver;
}

abstract public void Execute();

}

//将一个接收者对象绑定于一个动作,调用接收者相应的操作,以实现Execute。
class ConcreteCommand : Command
{
public ConcreteCommand(Receiver receiver) : base(receiver)
{
}

public override void Execute()
{
receiver.Action();
receiver.Action1();
}
}

//要求该命令执行这个请求
class Invoker
{
Command command;
public void SetCommand(Command command)
{
this.command = command;
}

public void ExecuteCommand()
{
command.Execute();
}

}

调用:

Receiver r = new Receiver();
Command c = new ConcreteCommand(r);
Invoker i = new Invoker();
i.SetCommand(c);
i.ExecuteCommand();

 

//松耦合

//烧肉串者
public class Barbecuer
{
public void BakeMutton() { Console.WriteLine("烧肉串!"); }
public void BakeChickenWing() { Console.WriteLine("烧鸡翅!"); }
}

//抽象命令基类

public abstract class Command
{
protected Barbecuer receiver;
public Command(Barbecuer receiver)
{
this.receiver = receiver;
}
public abstract void ExecuteCommand();
}

//命令基类实现

class BakeChickenWingCommand : Command
{
public BakeChickenWingCommand(Barbecuer receiver) : base(receiver)
{
}

public override void ExecuteCommand()
{
receiver.BakeChickenWing();
}
}

class BakeMuttonCommand : Command
{
public BakeMuttonCommand(Barbecuer receiver) : base(receiver)
{
}

public override void ExecuteCommand()
{
receiver.BakeMutton();
}
}

//服务员类

class Waiter
{
//增加存放具体命令的容器
IList<Command> orders = new List<Command>();

//设置订单
public void SetOrder(Command command)
{
if(command.ToString()== "mlms2.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 (Command item in orders)
{
item.ExcuteCommand();
}
}

}

m.ExecuteCommand();

}
}

}

 

调用:

//开店前的准备
Barbecuer person = new Barbecuer();
Command cmd1 = new BakeMuttonCommand(person);
Command cmd2 = new BakeMuttonCommand(person);
Command cmd3 = new BakeChickenWingCommand(person);
Waiter waiter = new Waiter();

//开门营业 顾客点菜
waiter.SetOrder(cmd1);
waiter.SetOrder(cmd2);
waiter.SetOrder(cmd3);

//点菜完毕,通知厨房
waiter.Notify();

waiter.CancelOrder(cmd3);

 

设计模式--命令模式