Design Patterns Java - Memento Php

1) What have we done?

We created object "Memento" which has record of stated object "ClassA"

"Memento" contains two methods "setState" and "getState" in order to return stated of given object.
In "ClassA" we created two methods:
- "createMemento" for store current state of object
- "setMemento" to inject previous state.


import java.util.HashMap;
import java.util.Map;

public class Memento
{
    protected Map<String, Object> state = new HashMap<>();

    public Map<String, Object> getState()
    {
        return state;
    }

    public Memento setState(Map<String, Object> state)
    {
        this.state = state;
        return this;
    }
}

import java.util.HashMap;
import java.util.Objects;

public class ClassA
{
    private String attribue;

    public ClassA(String attribue)
    {
        this.attribue = attribue;
    }

    public void doSomething()
    {
        System.out.println("Doing something with attribute " + attribue);
    }

    public void setAttribue(String attribue)
    {
        this.attribue = attribue;
    }

    public Memento createMemento()
    {
        return new Memento().setState(new HashMap<String, Object>()
        {
            {
                put("attribute", attribue);
            }
        });
    }

    public void setMemento(Memento memento)
    {
        attribue = (String) memento.getState().get("attribute");
    }
}




2) Is our goal was achieved?

Definitely yes, let's see on Client

We just create "Memento" before "setAttribute" and after it we restore previous state.


public class Client
{
    public static void main(String[] args)
    {
        ClassA classA = new ClassA("value1");

        Memento memento = classA.createMemento();

        classA.setAttribue("value2"); // we want to possibility of undo this action

        classA.setMemento(memento); // yes we can undo now

        classA.doSomething();
    }
}