Search code examples
c++qtmodel-view-controllerdesign-patternsmemento

Memento Pattern and MVC pattern, originator state will be alway duplicated?


I've start implement the undo&redo via the Memento Pattern, my progress till now are those:

from Class Controller, function RGB(...):

void Controller::rgb(int exp, double cont, int r, int g, int b){

    originator->setValue(exp, originator->exposure_Val);
    originator->setValue(cont, originator->contrast_Val);
    originator->setValue(r, originator->red_Val);
    originator->setValue(g, originator->green_Val);
    originator->setValue(b, originator->blue_Val);

    caretaker->setMemento(originator->createMemento());

    RGB_process run(model->src, model->dst, exp, cont, r, g, b);
    run.doProcess();
    model->setValue(exp, cont, r, g, b);
}

void Model::setValue(...):

....code that sets values...

notify(); //notify observer, and update the view

then from my view, on_undo_btn(...):

void MainWindow::on_undo_btn_clicked()
{
    controller->originator->restoreToMemento(controller->caretaker->getMemento());

    ui->exposure_slider->setValue(controller->originator->getValue(controller->originator->exposure_Val));
    ui->contrast_slider->setValue(controller->originator->getValue(controller->originator->contrast_Val));
    ui->red_slider->setValue(controller->originator->getValue(controller->originator->red_Val));
    ui->green_slider->setValue(controller->originator->getValue(controller->originator->green_Val));
    ui->blue_slider->setValue(controller->originator->getValue(controller->originator->blue_Val));
}

My problem is: every time I press on the "undo" btn, as it updates the sliders values, my Memento will be re-recorded as the controller is triggered, so that I got 2 equal states of my momentum. Now, this is not bad at all, as I would like to implement a "redo" also, so my thought was to Push this "duplicate" in front of my actual state, in order to be able to go "back from the undo". How can I implement such a condition? Is better to change approach and record my Memento States everywhere else?


Solution

  • Controller now got a " bool undoing " values to skip the observer notification.