设计模式之命令模式

来源:互联网 发布:宁德电脑数据恢复专家 编辑:程序博客网 时间:2024/04/29 17:43

命令模式:

将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。命令模式又称为动作(Action)模式或事务(Transaction)模式。


以下情况可以考虑使用命令模式:

  1. 系统需要将请求调用者和请求接收者解耦,使得调用者和接收者不直接交互
  2. 系统需要在不同的时间指定请求、将请求排队和执行请求
  3. 系统需要支持命令的撤销(Undo)操作和恢复(Redo)操作
  4. 系统需要将一组操作组合在一起,即支持宏命令

命令模式UML图:


下面是一个使用遥控器来控制电灯的例子:

package pattern.command;public class CommandPatternTest{    /**     * @param args     */    public static void main(String[] args)    {        LightOnCommand lightOnCommand = new LightOnCommand(new Light());        LightOnCommand lightOffCommand = new LightOnCommand(new Light());                RemoteControl control = new RemoteControl();        control.setCommand(lightOnCommand);        control.executeCommand();                control.setCommand(lightOffCommand);        control.executeCommand();    }}interface Command{    void execute();}class LightOnCommand implements Command{    private Light light;        public LightOnCommand(Light light)    {        this.light =  light;    }        @Override    public void execute()    {        System.out.println("concrete command. executing...");        light.on();    }    }class LightOffCommand implements Command{    private Light light;        public LightOffCommand(Light light)    {        this.light =  light;    }        @Override    public void execute()    {        System.out.println("concrete command. executing...");        light.off();    }    }class RemoteControl{    private Command command;        public void setCommand(Command command)    {        this.command = command;    }        public void executeCommand()    {        command.execute();    }}class Light{    public void on()    {        System.out.println("Light on.");    }        public void off()    {        System.out.println("Light off.");    }}

参考资料:

 设计模式 ( 十三 ) 命令模式Command(对象行为型)

《Head First 设计模式》

原创粉丝点击