文章目录
package com.example.demo.designpattern;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class Memento {
private String label;
private String pageName;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getPageName() {
return pageName;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
}
class OriginatorPage {
private String label;
private String pageName;
private String title;
public void setLabel(String label) {
this.label = label;
}
public void setPageName(String pageName) {
this.pageName = pageName;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "OriginatorPage{" +
"label='" + label + '\'' +
", pageName='" + pageName + '\'' +
'}';
}
public Memento createMemento(){
Memento memento = new Memento();
memento.setLabel(this.label);
memento.setPageName(this.pageName);
return memento;
}
public void restoreMemento(Memento memento){
this.setLabel(memento.getLabel());
this.setPageName(memento.getPageName());
}
}
class MementoCaretaker {
public volatile AtomicInteger index = new AtomicInteger(-1);
private ArrayList<Memento> mementoList = new ArrayList<>();
public Memento getMemento(int i) {
return mementoList.get(i);
}
public void addMemento(Memento memento) {
index.incrementAndGet();
mementoList.add(memento);
}
}
class BrowserClient {
public static void main(String[] args) {
OriginatorPage page = new OriginatorPage();
page.setPageName("123");
page.setLabel("www.123.com");
page.setTitle("123");
href(page);
page.setPageName("456");
page.setLabel("www.456.com");
page.setTitle("456");
href(page);
back(page);
forward(page);
}
private static MementoCaretaker mementoCaretaker = new MementoCaretaker();
public static void href(OriginatorPage page) {
mementoCaretaker.addMemento(page.createMemento());
System.out.println(page);
}
public static void back(OriginatorPage page) {
int i = mementoCaretaker.index.decrementAndGet();
if (i < 0) {
System.out.println("no-history");
return;
}
page.restoreMemento(mementoCaretaker.getMemento(i));
System.out.println("back-to:" + page);
}
public static void forward(OriginatorPage page) {
Memento memento = mementoCaretaker.getMemento(mementoCaretaker.index.incrementAndGet());
if (memento == null) {
System.out.println("nothing-to-forward");
return;
}
page.restoreMemento(memento);
System.out.println("forward-to:" + page);
}
}