Multiple Originators in Memento

43 views Asked by At

I have been given code for a game. My assignment is now have button to save the state of this game and to restore it this saved state. In the code there is a Game Window and there is a Game Engine (main loop and logic).

I want to apply the memento pattern here. Initially, I thought that I could make the game engine the originator since here the references to classes that need to be reset are stored (e.g. Player): in this class is my save memento where I copy the variables and set it in the memento + restores memento where I reset the variables from the memento.

However, in Game Window there now also appears to be some variable stored that I need to save and reset in the Memento. Therefore, I now am wondering if I could have multiple originators: so both classes save to the memento and both restore? I still would have one memento class and one caretaker.

Now, I am wondering if it is possible in the memento pattern to have multiple originators and if this seems like a good design? Or otherwise what are other options I can do?

1

There are 1 answers

0
Peter Dongan On

Yes. What I did to achieve this was to put the memento implementation into a service. You can inject that service anywhere you want to use it. The implementation is on GitHub.

https://github.com/peterdongan/UndoService

This project includes an aggregate undo service, which allows you to track different parts of the state separately but still used unified undo-redo functionality. However, this is unnecessary for your purposes because you are only tracking one thing from different places. All you need to do is to inject it wherever you are using it.