mardi 6 juin 2017

How to design a model to allow apply or cancel updates?

Is there a design or development pattern where we deal with making updates to a copy of the actual data and applying the diff to the original reference if needed?

If not, what is the best way of designing such models?

What I think I should do-

  1. I should probably use an enum mode to indicate whether the model is being used in 'Update direct reference mode' OR 'Update only a copy mode'
  2. Update the setters and getters of data to reference the actualState or the temporaryState as per what mode is the model being used in.
  3. Have the setter method for mode to create a copy of the actual data and store it in a temporary state. If the mode is updated to update direct reference, clear out the temporaryState
  4. Create a method for applying the changes from temporaryState to the actualState. This method shall also clear out the temporary state from memory.

e.g.

enum InsertionMode {
    UPDATE_DIRECT, UPDATE_COPY
}

class Store {
  private Data actualState;
  private Data temporaryState;
  private InsertionMode mode;

  private void resetTemporaryState() {
    ....
  }

  private void initTemporaryState() {
    this.temporaryState = copy(actualState);
  }

  private commitTemporaryState() {
    this.actualState = this.temporaryState;
    this.resetTemporaryState();
  }

  public Data setInsertionMode(InsertionMode mode) {
    if (this.mode != mode) {
        InsertionMode previousMode = this.mode;
        this.mode = mode;

        if (previousMode == InsertionMode.UPDATE_COPY) {
            this.resetTemporaryState();
        }
        if (this.mode == InsertionMode.UPDATE_COPY) {
            this.initTemporaryState();
        }
    }
  }

  public void commit() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.commitTemporaryState();
    }
  }

  public void abort() {
    if (this.mode == InsertionMode.UPDATE_COPY) {
        this.resetTemporaryState();
        this.setInsertionMode(InsertionMode.UPDATE_DIRECT);
    }
  }

  ...
}

Aucun commentaire:

Enregistrer un commentaire