3. 行为型模式 (7) 备忘录模式

阅读更多
3. 行为型模式 (7) 备忘录模式

备忘录模式(Memento Pattern)保存一个对象的某个状态,以便在适当的时候恢复对象。

在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样可以在以后将对象恢复到原先保存的状态。


1. 备忘录模式

package com.andrew.pattern0307.memento.model01;
public class Memento {
    private String state;
    public Memento(String state) {
        this.state = state;
    }
    public String getState() {
        return state;
    }
}


package com.andrew.pattern0307.memento.model01;
public class Originator {
    private String state;
    public void setState(String state) {
        this.state = state;
    }
    public String getState() {
        return state;
    }
    public Memento saveStateToMemento() {
        return new Memento(state);
    }
    public void getStateFromMemento(Memento Memento) {
        state = Memento.getState();
    }
}


package com.andrew.pattern0307.memento.model01;
import java.util.ArrayList;
import java.util.List;
public class CareTaker {
    private List mementoList = new ArrayList();
    public void add(Memento state) {
        mementoList.add(state);
    }
    public Memento get(int index) {
        return mementoList.get(index);
    }
}


package com.andrew.pattern0307.memento.model01;
/**
 * 1. 备忘录模式
 * 
 * @author andrew
 * @date 2018/08/20
 */
public class Client {
    public static void main(String[] args) {
        Originator originator = new Originator();
        CareTaker careTaker = new CareTaker();
        originator.setState("State #1");
        originator.setState("State #2");
        careTaker.add(originator.saveStateToMemento());
        originator.setState("State #3");
        careTaker.add(originator.saveStateToMemento());
        originator.setState("State #4");    
        System.out.println("Current State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(0));
        System.out.println("First saved State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(1));
        System.out.println("Second saved State: " + originator.getState());
    }
}
运行结果:
Current State: State #4
First saved State: State #2
Second saved State: State #3

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