7命令模式

图片来自head first 设计模式,仅供学习之用

 命令模式是对对象的操作进行封装,封装的方式就是定义抽象的命令接口,在接口中定义一组操作。具体的命令类要持有命令的接受者。此外命令还需要有一个容器来存放。不过对这个容器的作用我很是疑惑,我感觉没有这个invoker好像也没什么问题= =唯一的解释就是invoker可以存放不同种类的的命令,通过多态的方式。

简单的贴一下head first上的代码:

package com.company;

interface Command{
    public void excecute();
}
class Light{
    private String name;
    boolean isOn=false;
    public void open(){
        if (isOn ) {
            System.out.println("light is already on");
        }
        else{
            System.out.println("light is opened");
            isOn=true;
        }
    }
    public void close(){
        if (isOn ) {
            System.out.println("light is closed");
            isOn=false;
        }
        else System.out.println("light is already closed");

    }
}
class LightOnCommand implements Command{
    private Light light;
    public LightOnCommand(Light light){
        this.light=light;
    }
    @Override
    public void excecute() {
        light.open();
    }
}
class LightCloseCommand implements Command{
    private Light light;
    public LightCloseCommand(Light light){
        this.light=light;
    }

    @Override
    public void excecute() {
        light.close();
    }
}
class SimpleRemoteControl{
    private Command command;
    public SimpleRemoteControl(){
    }
    public void setCommand(Command command){
        this.command=command;
    }
    public void buttonPressed(){
        command.excecute();
    }
}
class CommandTestDrive{
    public static void test(){
        SimpleRemoteControl simpleRemoteControl=new SimpleRemoteControl();
        Light light=new Light();
        LightOnCommand lightOnCommand=new LightOnCommand(light);
        LightCloseCommand lightCloseCommand=new LightCloseCommand(light);
        simpleRemoteControl.setCommand(lightOnCommand);
        simpleRemoteControl.buttonPressed();
        simpleRemoteControl.setCommand(lightCloseCommand);
        simpleRemoteControl.buttonPressed();
    }
}

 

posted @ 2018-04-10 16:32  MalcolmMeng  阅读(140)  评论(0编辑  收藏  举报