命令模式:将请求封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
public interface Command { /** * 执行动作 * */ void execute(); /** * 撤销功能 * */ void undo(); }
public class Light { public void on(){ System.out.println("light is on"); } public void off(){ System.out.println("light is off"); } }
public class LightOnCommand implements Command{ private final Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } @Override public void undo() { System.out.println("undo"); } }
package com.em.command; /** * 遥控器 * Created by Administrator on 2018/1/6. */ public class RemoteControl { private Command command; public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } /** * 执行操作 * */ public void buttonWasPress(){ command.execute(); } public static void main(String[] args) { Light light = new Light(); LightOnCommand lightOnCommand = new LightOnCommand(light); RemoteControl remoteControl = new RemoteControl(); remoteControl.setCommand(lightOnCommand); //设置命令 remoteControl.buttonWasPress(); } }