Java 设计模式 之 备忘录模式
Posted verejava
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 设计模式 之 备忘录模式相关的知识,希望对你有一定的参考价值。
http://www.verejava.com/?id=16999143457673
package com.memento.theory;
import java.util.Stack;
public class TestMemento
{
public static void main(String[] args)
{
MementoContainer container=new MementoContainer();
Originator orig=new Originator();
orig.setState("工作总结");
container.push(orig.createMemento());
orig.setState("工作报告");
container.push(orig.createMemento());
orig.setState("工作报告新春快乐");
orig.show();
orig.setMemento(container.back());
orig.show();
orig.setMemento(container.back());
orig.show();
orig.setMemento(container.forward());
orig.show();
orig.setMemento(container.forward());
orig.show();
}
}
package com.memento.theory;
public class Originator
{
private String state;
public Originator()
{
super();
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public Memento createMemento()
{
return new Memento(state);
}
public void setMemento(Memento memento)
{
this.state = memento.getState();
}
public void show()
{
System.out.println(state);
}
}
package com.memento.theory;
public class Memento
{
private String state;
public Memento(String state)
{
super();
this.state = state;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
}
package com.memento.theory;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MementoContainer
{
private Stack<Memento> mementos;
private int index;
public MementoContainer()
{
mementos=new Stack<Memento>();
}
public void push(Memento memento)
{
mementos.push(memento);
index++;
}
public Memento forward()
{
Memento memento=(Memento)mementos.get(index);
index++;
return memento;
}
public Memento back()
{
index--;
Memento memento=(Memento)mementos.get(index);
return memento;
}
}
http://www.verejava.com/?id=16999143457673
以上是关于Java 设计模式 之 备忘录模式的主要内容,如果未能解决你的问题,请参考以下文章