命令模式(Command):将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
优点:1、它能较容易的设计一个命令队列;2、在需要的情况下,可以较容易的将命令记入日志;3、允许接收请求的一方决定是否要否决请求;4、可以容易的实现对请求的撤销和重做;5、由于加入新的具体命令类不影响其它的类,因此增加新的具体命令类很容易。6、命令模式把请求一个操作的对象与知道怎么执行一个操作的对象分割开。
场景:在需要对请求操作支持撤销/恢复功能时。
/** * Created by hero on 16-4-7. */ public abstract class Command { protected Barbecuer receiver; public abstract void excuteCommand(); public Command(Barbecuer receiver) { this.receiver = receiver; } } /** * Created by hero on 16-4-7. */ public class BakeChickenWingCommand extends Command { @Override public void excuteCommand() { receiver.bakeChickenWing(); } public BakeChickenWingCommand(Barbecuer receiver) { super(receiver); } } /** * Created by hero on 16-4-7. */ public class BakeMuttonCommand extends Command { @Override public void excuteCommand() { receiver.bakeMutton(); } public BakeMuttonCommand(Barbecuer receiver) { super(receiver); } } /** * Created by hero on 16-4-7. */ public class Barbecuer { public void bakeMutton() { System.out.println("烤羊肉串"); } public void bakeChickenWing() { System.out.println("烤鸡翅"); } } import java.util.LinkedList; import java.util.List; /** * Created by hero on 16-4-7. */ public class Waitress { private List<Command> orders = new LinkedList<>(); public void setOrders(Command command) { //在此处可以拒绝某些command,当执行该command未满足条件时 TODO orders.add(command); } public void cancleOrder(Command command) { orders.remove(command); } public void notifyCook() { for (Command c : orders) { c.excuteCommand(); } } } public class Main { public static void main(String[] args) { Barbecuer cook = new Barbecuer(); BakeChickenWingCommand c1 = new BakeChickenWingCommand(cook); BakeMuttonCommand c2 = new BakeMuttonCommand(cook); Waitress waitress = new Waitress(); waitress.setOrders(c1); waitress.setOrders(c2); waitress.notifyCook(); } }