/**命令的执行者(接收者),可以看做是电视 */
public class Receiver {
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 ICommand {
public void execute();
}
/**命令接口实现类 ConcreteCommand,通常会持有接收者,并调用接收者的功能来完成命令要执行的操作*/
class CommandOn implements ICommand {
private Receiver receiver;
/**持有一个接收者对象 */
public CommandOn(Receiver receiver) {
this.receiver = receiver;
}
@Override
/**最终是通过调用接收者的方法,来完成命令要执行的操作*/
public void execute() {
receiver.turnOn();
}
}
//关机命令
class CommandOff implements ICommand {
private Receiver receiver;
public CommandOff(Receiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
receiver.turnOff();
}
}
//频道切换命令
class CommandChange implements ICommand {
private Receiver receiver;
private int channel;
public CommandChange(Receiver receiver, int channel) {
this.receiver = receiver;
this.channel = channel;
}
public void execute() {
receiver.changeChannel(channel);
}
}
/**命令的调用者(请求方),接收命令,并执行命令,可以看作是遥控器*/
public class Invoker {
private ICommand onCommand, offCommand, changeChannel;
public Invoker(ICommand onCommand, ICommand offCommand, ICommand changeChannel) {
this.onCommand = onCommand;
this.offCommand = offCommand;
this.changeChannel = changeChannel;
}
/**执行该命令 */
public void turnOn() {
onCommand.execute();
}
public void turnOff() {
offCommand.execute();
}
public void changeChannel() {
changeChannel.execute();
}
}
public class Test {
public static void main(String[] args) {
// 命令接收者(电视)
Receiver receiver = new Receiver();
// 不同的命令(开机、换台、关机)
ICommand on = new CommandOn(receiver);
ICommand off = new CommandOff(receiver);
ICommand channel = new CommandChange(receiver, new Random().nextInt(100));
// 命令控制对象(遥控器)
Invoker invoker = new Invoker(on, off, channel);
// 执行命令
invoker.turnOn();
invoker.changeChannel();
invoker.turnOff();
}
}