命令接口
命令具体类
命令接收者
命令发送者
public interface Command {
void turnOff();
void turnOn();
}
public class TurnOnCommand implements Command {
Light light;
public TurnOnCommand(Light light) {
this.light = light;
}
@Override
public void turnOff() {
light.turnOff();
}
@Override
public void turnOn() {
light.turnOn();
}
}
public class Light {
public void turnOn(){
System.out.println("开灯");
}
public void turnOff(){
System.out.println("关灯");
}
}
public class Actor {
Command command;
public Actor(Command command) {
this.command = command;
}
public void executeTurnOn(){
command.turnOn();
}
public void executeTurnOff(){
command.turnOff();
}
}
测试
public class Test {
public static void main(String[] args) {
Actor actor = new Actor(new TurnOnCommand(new Light()));
actor.executeTurnOn();
actor.executeTurnOff();
}
}
网友评论