平时我们下馆子吃各种各样的美食时,总会发现我们都是通过服务员来点餐的,而不会直接告诉厨师我们想吃什么。这其中就包含一个设计模式--命令模式。
代码结构图:
public abstract class Command { protected Barbecuer receiver; public Command(Barbecuer receiver){ this.receiver = receiver; } public abstract void executeCommand(); }
public class BakeWingCommand extends Command{ public BakeWingCommand(Barbecuer receiver){ super(receiver); } @Override public void executeCommand() { // TODO Auto-generated method stub receiver.bakeChickenWing(); } }
public class BakeMuttonCommand extends Command{ public BakeMuttonCommand(Barbecuer receiver){ super(receiver); } @Override public void executeCommand() { // TODO Auto-generated method stub receiver.bakeMutton(); } }
public class Barbecuer { public void bakeMutton(){ System.out.println("烤羊肉串"); } public void bakeChickenWing(){ System.out.println("烤鸡翅"); } }
public class Waiter1 { private List<Command> orders = new ArrayList<Command>(); public void setOrder(Command command){ orders.add(command); System.out.println("增加菜单:" + new Date()); } //取消订单 public void cancelOrder(Command command){ orders.remove(command); System.out.println("取消订单:" + new Date()); } public void orderNotify(){ for(Command cmd : orders){ cmd.executeCommand(); } } }
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Barbecuer boy = new Barbecuer(); Command bakeMutton1 = new BakeMuttonCommand(boy); Command bakeMutton2 = new BakeMuttonCommand(boy); Command bakeChickenWing = new BakeWingCommand(boy); Waiter1 girl1 = new Waiter1(); girl1.setOrder(bakeMutton1); girl1.setOrder(bakeMutton2); girl1.setOrder(bakeChickenWing); girl1.orderNotify(); } }
命令模式: 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
命令模式的作用:
1.能较容易地设计一个命令队列。
2.在需要的情况下,可以较容易地将命令记入日志。
3.允许接受请求的一方决定是否要否决请求。
4.可以容易地实现请求的撤销和重做。
5.由于加进新的命令模式不影响其他类,因此增加新的具体命令很容易。