public interface Command {
public void execute();
public void undo();
}public class LightOnCommand implements Command{
Light light;
public LightOnCommand(Light light){
this.light = light;
}
@Override
public void execute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}public class LightOffCommand implements Command{
Light light;
public LightOffCommand(Light light) {
super();
this.light = light;
}
@Override
public void execute() {
light.off();
}
@Override
public void undo() {
light.on();
}
}
public class FanOnCommand implements Command{
Fan fan;
public FanOnCommand(Fan fan) {
super();
this.fan = fan;
}
@Override
public void execute() {
fan.on();
}
@Override
public void undo() {
fan.off();
}
}public class FanOffCommand implements Command{
Fan fan;
public FanOffCommand(Fan fan) {
super();
this.fan = fan;
}
@Override
public void execute() {
fan.off();
}
@Override
public void undo() {
fan.on();
}
}
public class Control {
Command onCommand;
Command offCommand;
Command command;
public void setCommand(Command oncom,Command offcom){
onCommand = oncom;
offCommand = offcom;
}
public void on(){
command = onCommand;
onCommand.execute();
}
public void off(){
command = offCommand;
offCommand.execute();
}
public void undo(){
command.undo();
}
}
public class TestCommand {
public static void main(String[] args) {
Light light = new Light();
Fan fan = new Fan();
LightOffCommand lightOff = new LightOffCommand(light);
LightOnCommand lightOn = new LightOnCommand(light);
Control con = new Control();
con.setCommand(lightOn, lightOff);
con.on();
con.undo();
con.off();
FanOffCommand fanOffCommand = new FanOffCommand(fan);
FanOnCommand fanOnCommand = new FanOnCommand(fan);
con.setCommand(fanOnCommand, fanOffCommand);
con.on();
con.undo();
con.off();
}
}
命令模式
最新推荐文章于 2024-08-15 21:18:52 发布