public class Tv { public int currentChannel = 0; public void turnOn() { System.out.println("The televisino is on."); } public void turnOff() { System.out.println("The television is off."); } public void changeChannel(int channel) { this.currentChannel = channel; System.out.println("Now TV channel is " + channel); }}
//執行命令的接口
public interface Command { void execute();}
//開機命令
public class CommandOn implements Command { private Tv myTv; public CommandOn(Tv tv) { myTv = tv; } public void execute() { myTv.turnOn(); }}
//關機命令
public class CommandOff implements Command { private Tv myTv; public CommandOff(Tv tv) { myTv = tv; } public void execute() { myTv.turnOff(); }}
//頻道切換命令
public class CommandChange implements Command { private Tv myTv; private int channel; public CommandChange(Tv tv, int channel) { myTv = tv; this.channel = channel; } public void execute() { myTv.changeChannel(channel); }}
//可以看作是遙控器吧
public class Control { private Command onCommand, offCommand, changeChannel; public Control(Command on, Command off, Command channel) { onCommand = on; offCommand = off; changeChannel = channel; } public void turnOn() { onCommand.execute(); } public void turnOff() { offCommand.execute(); } public void changeChannel() { changeChannel.execute(); }}
//測試類
public class Client { public static void main(String[] args) { // 命令接收者 Tv myTv = new Tv(); // 開機命令 CommandOn on = new CommandOn(myTv); // 關機命令 CommandOff off = new CommandOff(myTv); // 頻道切換命令 CommandChange channel = new CommandChange(myTv, 2); // 命令控制對象 Control control = new Control(on, off, channel); // 開機 control.turnOn(); // 切換頻道 control.changeChannel(); // 關機 control.turnOff(); }}