將請求封裝成物件,可將此物件參數化,可用於操作日誌.佇列.還原等行為
主要分為
- Invoker
- 只負責執行invoke(),不關心物件及細節
- 可在此放進還原或是其他動作
- Receiver
- 請求所有細節在此決定(Ex. TV 有 on(), off() )
- Command
- 相關動作execute()的實作
public class Invoker {
List<Command> commands = new LinkedList<>();
public void addCommand(Command command){
commands.add(command);
}
public void invoke(){
for (Command command : commands) {
command.execute();
}
}
}
public class TV {
private String location = "";
public TV(String location) {
this.location = location;
}
public void on(){
System.out.println(location + " TV is on");
}
public void off(){
System.out.println(location + " TV is off");
}
}
public interface Command {
public void execute();
}
public class TVOnCommand implements Command {
TV tv;
public TVOnCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.on();
}
}
public class TVOffCommand implements Command {
TV tv;
public TVOffCommand(TV tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.off();
}
}
public class Test {
public static void main(String[] args) {
Invoker invoker = new Invoker();
TV tv = new TV("Living Room");
TVOnCommand tvOnCommand = new TVOnCommand(tv);
TVOffCommand tvOffCommand = new TVOffCommand(tv);
invoker.addCommand(tvOnCommand);
invoker.addCommand(tvOffCommand);
invoker.invoke();
}
}
Result:
Living Room TV is on
Living Room TV is off