命令模式

来源:互联网 发布:小型公司网络布线 编辑:程序博客网 时间:2024/05/18 11:13

命令模式就是把方法调用封装起来,将动作请求者和动作实行者隔离开。

public class RemoteControl {    List<Command> onCommands;    List<Command>  offCommands;    public RemoteControl(){        onCommands=new ArrayList<>();        offCommands=new ArrayList<>();    }    public void addCommand(Command onCommand,Command offCommand){        onCommands.add(onCommand);        offCommands.add(offCommand);    }    public void onButtonWasPushed(int slot){        onCommands.get(slot).execute();    }    public void offButtonWasPushed(int slot){        offCommands.get(slot).execute();    }    public String toString(){        return "";    }}命令public interface Command {    void execute();    void undo();}public class LightOffCommand implements Command {    Light light;    public LightOffCommand(Light light) {        this.light = light;    }    @Override    public void execute() {        light.off();    }    @Override    public void undo() {    }}public class Light {    public void on() {    }    public void off() {    }}具体命令中控制目标的行为
原创粉丝点击