15 Oct 2014

Java设计模式:备忘录模式

注:本文为译文,原文出处java-design-patterns-in-stories

未来, 时间旅行终将被发明. 备忘录就是时间旅行的关键. 主要的是, 它所做的是允许一个对象回溯到一个状态.

在接下来的例子中, 你可以时间旅行到你生命中的任何年代, 并且可以恢复到已经去过的之前的一个年代.

备忘录模式类图

memento design pattern

备忘录模式Java代码

package designpatterns.memento;
import java.util.List;
import java.util.ArrayList;
class Life {
    private String time;

    public void set(String time) {
        System.out.println("Setting time to " + time);
        this.time = time;
    }

    public Memento saveToMemento() {
        System.out.println("Saving time to Memento");
        return new Memento(time);
    }

    public void restoreFromMemento(Memento memento) {
        time = memento.getSavedTime();
        System.out.println("Time restored from Memento: " + time);
    }

    public static class Memento {
        private final String time;

        public Memento(String timeToSave) {
            time = timeToSave;
        }

        public String getSavedTime() {
            return time;
        }
    }
}

public class You {
    public static void main(String[] args) {
        List<Life.Memento> savedTimes = new ArrayList<Life.Memento>();

        Life life = new Life();

        //time travel and record the eras
        life.set("2000 B.C.");
        savedTimes.add(life.saveToMemento());
        life.set("2000 A.D.");
        savedTimes.add(life.saveToMemento());
        life.set("3000 A.D.");
        savedTimes.add(life.saveToMemento());
        life.set("4000 A.D.");

        life.restoreFromMemento(savedTimes.get(0));

    }
}

Tags:
0 comments