public class Light {
public void on() {
System.out.println("灯点亮");
}
public void off() {
System.out.println("灯熄灭");
}
}
public class TV {
public void on() {
System.out.println("TV打开");
}
public void off() {
System.out.println("TV关闭");
}
}
public interface Command {
void execute();
}
public class LightOnCommand implements Command{
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override public void execute() {
light.on();
}
}
public class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override public void execute() {
light.off();
}
}
public class TVOnCommand implements Command{
private TV tv;
public TVOnCommand(TV tv) {
this.tv = tv;
}
@Override public void execute() {
tv.on();
}
}
public class TVOffCommand implements Command{
private TV tv;
public TVOffCommand(TV tv) {
this.tv = tv;
}
@Override public void execute() {
tv.off();
}
}
public class SwitchInvoker {
private Command onCommand;
private Command offCommand;
public void setOnCommand(Command onCommand) {
this.onCommand = onCommand;
}
public void setOffCommand(Command offCommand) {
this.offCommand = offCommand;
}
public void on(){
onCommand.execute();
}
public void off(){
offCommand.execute();
}
}
public class App {
public static void main(String[] args) {
Light light=new Light();
TV tv=new TV();
Command lightOnCommand=new LightOnCommand(light);
Command lightOffCommand=new LightOffCommand(light);
Command tvOnCommand=new TVOnCommand(tv);
Command tvOffCommand=new TVOffCommand(tv);
SwitchInvoker commonSwitch=new SwitchInvoker();
commonSwitch.setOnCommand(lightOnCommand);
commonSwitch.setOffCommand(lightOffCommand);
commonSwitch.on();
commonSwitch.off();
commonSwitch.setOnCommand(tvOnCommand);
commonSwitch.setOffCommand(tvOffCommand);
commonSwitch.on();
commonSwitch.off();
}
}