Search code examples
c++imagedesign-patternsundoundo-redo

Build an Undo & Redo by making a 'state snapshot'


I would like to build a Undo&Redo class for a image editor, without building the entire command pattern.

Actually in my code, I'm using the MVC pattern, and so I got a bunch of attributes that are updated every times I launch an action:

    class model{
    ...code...

public:
        bool is_Flipped_V = false;
        bool is_Flipped_H = false;
        bool is_Rotated = false;
        bool is_Blurred = false;
        bool is_Sharpened = false;
        bool is_Grayscale = false;
        bool is_Sepia = false;
        bool is_Loaded = false;
        bool is_Saved = false;


        int exposure_Val;
        double contrast_Val;
        int red_Val;
        int green_Val;
        int blue_Val;

        int hue_Val;
        int saturation_Val;
        int luminance_Val;

        int angle_Val;
    }

my idea would be to create a list, that every time the Observer is notified, it records the actual state of all the upper attributes. So that, when I want to 'undo' something, I can just re-update my image, by passing the previous attributes states.

Have someone ever done something like? How Can I save the states of the attributes in a list? Is there a different but better way to implement that?


Solution

  • The preferred way to implement Undo/Redo is to follow the Memento Pattern. It stores every undoable operation and allows to jump to any random point in the history. It's an easy and clean pattern that helps to implement this feature.

    The Memento pattern uses three actor classes. Memento contains the actual state of an object to be restored. Originator creates and stores states in Memento objects and the Caretaker object is responsible to restore an object's state from a collection of Memento objects.