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

posted @ 2018-06-28 09:23  verejava  阅读(135)  评论(0编辑  收藏  举报