mercredi 7 décembre 2022

How to log when using Command Pattern

Head First Design Patterns say:

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

Later the book said:

The semantics of some applications require that we log all actions and be able to recover after a crash by reinvoking those actions. The Command Pattern can support these semantics with the addition of two methods: store() and load(). In Java we could use object serialization to implement these methods, but the normal caveats for using serialization for persistence apply.

How does this work? As we execute commands, we store a history of them on disk. When a crash occurs, we reload the command objects and invoke their execute() methods in batch and in order.

I am trying to come up with an example code. The code I wrote till now is:

class Client {
    public static void main(String[] args) {
        Command enableCommand = new EnableCommand();
        enableCommand.execute();
    }
}

interface Command {
    void execute();
    void store();
    void load();
}

class EnableCommand implements Command {

    public EnableCommand() {
    }

    @Override
    public void execute() {
        store();
        System.out.println("Execute Command");
    }

    @Override
    public void store() {
        System.out.println("Storing on Disk");

    }

    @Override
    public void load() {
        // TODO Auto-generated method stub

    }
}

How the load() function is supposed to work?

Aucun commentaire:

Enregistrer un commentaire