命令模式
一、命令模式相关概念
命令模式:将具体的执行者封装成命令供调用者调用。
命令对象将调用者和执行者分离,调用者就不必去关心具体的执行过程,以达到解耦和易于维护的目的。
应用:线程池
二、UML图
三、代码
Command.java
public interface Command { void execute(); void undo(); }
LightCommand.java
public class LightCommand implements Command{ private Light l; LightCommand(Light l) { this.l = l; } public void execute() { l.on(); } public void undo() { l.off(); } }
Light.java
public class Light { void on() { System.out.println("Light on"); } void off() { System.out.println("Light off"); } }
RemoteControl.java
public class RemoteControl { Command c; boolean flag = true; RemoteControl() { } void setCommand(Command c) { this.c = c; } void botton() { if(flag) { c.execute(); flag = false; }else { c.undo(); flag = true; } } }
Test.java
public class Test { public static void main(String[] args) { Light l = new Light(); Command lc = new LightCommand(l); RemoteControl rc = new RemoteControl(); rc.setCommand(lc); rc.botton(); rc.botton(); } }