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 编程基础
上一篇Java 设计模式 之 调停者模式
下一篇Java 设计模式 之 观察者模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭