设计模式(18)-备忘录模式

定义

将对象的状态备份,以便进行回滚操作.


示例

备忘录模式应用较多,如jdbc回滚操作,游戏的存档等.


1.需要备忘对象类

public class Originator {
    //对象状态
    private String state = "";

    public String getState(){
        return this.state;
    }

    public void setState(String state){
        this.state = state;
    }

    public void changeState(String state){
        this.state = state;
    }
    //创建备忘录
    public Memento createMemento(){
        return new Memento(this.state);
    }

    //恢复备忘录状态
    public void restoreMemento(Memento memento){
        this.state = memento.getState();
    }
}

2.备忘录类

public class Memento {
    private String state;

    public Memento(String state){
        this.state = state;
    }

    public String getState(){
        return this.state;
    }

    public void setState(String state){
        this.state = state;
    }
}

3.备忘录管理类

public class Caretaker {
    private Memento memento;

    public Caretaker(Memento memento){
        this.memento = memento;
    }

    public Memento getMemento(){
        return this.memento;
    }

    public void setMemento(Memento memento){
        this.memento = memento;
    }
}

4.运行

public class Client {
    public static void main(String[] args) {
        Originator originator = new Originator();

        originator.setState("good");
        System.out.println("对象的初始状态为:"+originator.getState());

        Caretaker caretaker = new Caretaker(originator.createMemento());

        originator.changeState("bad");
        System.out.println("改变后的状态为:"+originator.getState());

        originator.restoreMemento(caretaker.getMemento());
        System.out.println("恢复后的状态为:"+originator.getState());
    }
}

结果:

对象的初始状态为:good
改变后的状态为:bad
恢复后的状态为:good

6.基于clone()的变种

public class OriginatorB implements Cloneable{
    //备忘录
    private OriginatorB backup;

    private String state;

    public String getState(){
        return this.state;
    }

    public void setState(String state){
        this.state = state;
    }

    //创建备忘录
    public void createMemento(){
        this.backup = this.clone();
    }

    //从备忘录中恢复状态
    public void restoreMemento(){
        this.setState(this.backup.getState());
    }

    //实现clone方法
    protected OriginatorB clone(){
        try {
            return (OriginatorB) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        OriginatorB originatorB = new OriginatorB();
        originatorB.setState("good!!!");
        System.out.println(originatorB.getState());
        originatorB.createMemento();

        originatorB.setState("bad!!!");
        System.out.println(originatorB.getState());

        originatorB.restoreMemento();
        System.out.println(originatorB.getState());
    }
}

结果:

对象的初始状态为:good
改变后的状态为:bad
恢复后的状态为:good

你可能感兴趣的:(设计模式)