设计模式(一):命令模式(4)——命令模式扩展之日志请求

前言

命令模式的讲解分为四篇:

设计模式(一):命令模式(1)——基本的命令模式

设计模式(一):命令模式(2)——命令模式扩展之宏命令

设计模式(一):命令模式(3)——命令模式扩展之队列请求

设计模式(一):命令模式(4)——命令模式扩展之日志请求

一、命令模式扩展之日志请求

1.日志请求的工作方式

上一节介绍了命令模式之队列请求,本节介绍一下另一个扩展——日志请求。某些用用需要将我们所有的动作都记录在日志中,并能在系统死机之后,重新调用这些动作恢复到之前的状态。命令模式能够支持这一点。这些技巧可以被应用到事务控制等操作的处理中。下面我们来模拟这样一个场景来实现日志请求的工作方式。我们会模拟电脑执行了几个动作命令并将日志存储在电脑中,然后模拟电脑在此刻死机,我们的数据此刻全部丢失。在电脑重启后,我们再通过加载存储的命令恢复数据。

2.代码实现

代码地址:https://github.com/wutianqi/desin-patterns/tree/master/design-pattern/src/main/java/com/wutqi/p1/command_pattern/p4/log

******************Computer*************************

/**
 * 电脑,命令调用者
 * @author wuqi
 * @Date 2019/1/30 15:46
 */
public class Computer {
    //执行的命令日志
    private List<Command> commandLogs;
    private Command command;

    public Computer(List<Command> commandLogs){
        this.commandLogs = commandLogs;
    }

    public void execute(){
        this.command.execute();
        commandLogs.add(command);
    }

    public void setCommand(Command command){
        this.command = command;
    }

    /**
     * 存储
     */
    public void store(){
        //存储命令日志,实际中是将其存储在文件中
        System.out.println("commandLogs is been stored");
    }

    /**
     * 加载
     */
    public void load(){
        //实际上是从文件中取出commandLogs然后执行之前执行过的命令对象
        for(Command c : commandLogs){
            c.execute();
        }
    }

}

 

******************ActionCommand*************************

/**
 * 动作命令
 * @author wuqi
 * @Date 2019/1/30 14:33
 */
public class ActionCommand implements Command {
    /**
     * 动作名称
     */
    private String name;

    public ActionCommand(String name){
        this.name = name;
    }

    @Override
    public void execute() {
        System.out.println("action " + name + " is been execute...");
    }

    @Override
    public void undo() {

    }
}

 

******************ActionCommandTest*************************

/**
 * @author wuqi
 * @Date 2019/1/30 14:37
 */
public class ActionCommandTest {
    public static void main(String[] args) {
        //创建存储执行命令的地方
        List<Command> commandLogs = new ArrayList<>();
        //创建命令的发出者,电脑
        Computer computer = new Computer(commandLogs);
        for(int i=0;i<5;i++){
            ActionCommand actionCommand = new ActionCommand("" + i);
            computer.setCommand(actionCommand);
            computer.execute();
        }
        //存储命令
        computer.store();
        try{
            //模拟电脑死机
            int a = 1/0;
        }catch (Exception e){
            System.out.println("the computer is bung!");
            //电脑重启,加载存储命令的文件并进行恢复,这里是从storedCommands中取储命令进行恢复。正常情况下应该先从文件中取出storeCommands,再执行
            System.out.println("the computer is restart,begin load action");
            computer.load();
        }

    }
}

 

执行结果:

二、总结

由命令模式实现日志请求的好处在于,如果我们操作的是大型的数据存储,我们不可能在每一次请求执行后立即将数据快速的保存下来,此时记录日志请求就先的十分重要了。

 

posted @ 2019-01-30 16:13  安静的boy  阅读(810)  评论(0编辑  收藏  举报