vendredi 23 septembre 2022

memento pattern - encapsulation and reusability of memento object

class Originator {
   private String state;
   Originator(String state) {
        this.state = state;
   }
   
   public void setState(String newState) {
        this.state = newState;
   }
   
   public Memento createMemento() {
        return new Memento(state);
   }
   
   public void restoreState(Memento memento) {
        // HOW to access private state of memento??
   }
}


class Memento {
   private String state;
   Memento(String state) {
        this.state = state;
   }
}


class CareTaker {
    public static void main(String[] args) {
        Originator originator = new Originator("state");
        Memento memento = originator.createMemento();
        
        originator.setState("new state");
        originator.restoreState(memento);
    }
}

I'm trying to implement memento pattern. I've made the state in Memento class private so that it is not accessible by caretaker. But on passing the memento object to originator, it will not be able to access the state of memento itself.

To resolve this, we can do few things, but there are disadvantages to it, thats why I didnt do them.

  1. Make state in memento public: The disadvantage is that it will not follow encapsulation of internal state.
  2. Make memento class internal to originator class: The disadvantage is that memento class will be bound to originator class and will not be reusable by other originators.
  3. Passing the originator reference in constructor of memento so that memento can itself restore the state of originator: The disadvantage is that memento class will be bound to single originator object and will not be reusable by other originators.

Please suggest solution where we follow encapsulation and we can also support reusability of memento object.

Aucun commentaire:

Enregistrer un commentaire