设计模式(四)之命令模式

命令接口:

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值