6.命令模式
Posted Kyhoon
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了6.命令模式相关的知识,希望对你有一定的参考价值。
1.定义命令接口
public interface Command { public void execute(); }
2.具体需要调用到的方法的类
public class Light { public void on(){ System.out.println("Light on"); } public void off(){ System.out.println("Light off"); } } public class GarageDoor { public void up(){ System.out.println("Garage Door is Open"); } public void down(){ System.out.println("Garage Door Down"); } public void stop(){ System.out.println("GarageDoor stop"); } public void lightOn(){ System.out.println("GarageDoor LightOn "); } public void lightOff(){ System.out.println("GarageDoor lIghOff"); } }
3.这些具体要调用到的方法的类的对应具体命令类
public class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light){ this.light=light; } public void execute() { // TODO Auto-generated method stub this.light.on(); } } public class GarageDoorOpenCommand implements Command{ private GarageDoor door; public GarageDoorOpenCommand(GarageDoor door){ this.door=door; } public void execute() { // TODO Auto-generated method stub this.door.up(); } }
4.客户程序
public class SimpleRemoteControl { private Command command; public void setCommand(Command command){ this.command=command; } public void buttonWasPressed(){ this.command.execute(); } }
5.应用
public class App { public static void main(String[] args) { SimpleRemoteControl control=new SimpleRemoteControl(); //1 Light light=new Light(); Command lightOn=new LightOnCommand(light); control.setCommand(lightOn); control.buttonWasPressed(); //2 GarageDoor door=new GarageDoor(); Command doorOpen=new GarageDoorOpenCommand(door); control.setCommand(doorOpen); control.buttonWasPressed(); } }
6.结果应该是这样的
tip: 而命令模式中,经典的批处理,撤销,重做。其实就是在客户程序中,比如用list集合缓存一批命令对象,批调用就实现了批处理,然后在每次调用时也缓存这次调用的命令方法,下次重新执行最后一次执行的相反的缓存命令或此缓存命令就实现撤销或重做了。
以上是关于6.命令模式的主要内容,如果未能解决你的问题,请参考以下文章