Memento pattern

The memento pattern provides the ability to restore the object's previous state without violation of the encapsulation principle.

problems

This pattern is useful for any editor application for an undo operation. It is also used in database transactions for rollback operations.

example

public class DemoObj{
    private int prop1=0;
    private int prop2=1;
    
    // ...
    
    public MementoState saveState(){
        return new MementoState(prop1, prop2);
    }

    public void restoreState(MementoState st){
        prop1 = st.prop1;
        prop2 = st.prop2;
    }

    public int getProp1() {return prop1;}
    public int getProp2() {return prop2;}


    public static class MementoState {
        int prop1=0;
        int prop2=1;
        
        public MementoState(int p1, int p2){
            prop1=p1;
            prop2=p2;
        }
    }
}