命令接口:
public interface Command {
public void executor();
}
执行命令的真正实体:
public class Diablo {
private int currentLevel = 0;
public void skillOne() {
System.out.println("百裂拳!");
}
public void skillTwo() {
System.out.println("金钟罩!");
}
public void changeLevel(int channel) {
this.currentLevel = channel;
System.out.println("Diablo level is" + currentLevel + ".");
}
}
命令一:
public class SkillOneCommand implements Command {
private Diablo game;
public SkillOneCommand(Diablo tv) {
this.game = tv;
}
@Override
public void executor() {
game.skillTwo();
}
}
命令二:
public class SkillTwoCommand implements Command {
private Diablo game;
public SkillTwoCommand(Diablo tv) {
this.game = tv;
}
@Override
public void executor() {
game.skillOne();
}
}
命令三:
public class ChangeLevelCommand implements Command {
private Diablo game;
private int level;
public ChangeLevelCommand(Diablo tv, int channel) {
this.game = tv;
this.level = channel;
}
@Override
public void executor() {
game.changeLevel(level);
}
}
控制器:
public class Control {
private Command skillOne, skillTwo, changeLevel;
public Control(Command skillOne, Command skillTwo,
Command changeLevel) {
this.skillOne = skillOne;
this.skillTwo = skillTwo;
this.changeLevel = changeLevel;
}
public void skillOne() {
skillOne.executor();
}
public void skillTwo() {
skillTwo.executor();
}
public void changeLevel() {
changeLevel.executor();
}
}
调用者:
public class Consumer {
public static void main(String[] args) {
Diablo game = new Diablo();
Command skillTwo = new SkillTwoCommand(game);
Command skillOne = new SkillOneCommand(game);
Command changeLevel = new ChangeLevelCommand(game, 5);
Control control = new Control(skillTwo, skillOne, changeLevel);
control.skillOne();
control.changeLevel();
control.skillTwo();
}
}
时间: 2024-10-28 21:21:37