码迷,mamicode.com
首页 > 其他好文 > 详细

备忘录模式

时间:2016-08-07 21:50:59      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并咋该对象之外保存这个状态


类图:

技术分享


代码:

public class Originator {

	private String state = "";
	
	public String getState(){
		return state;
	}
	
	public void setState(String state){
		this.state  =state;
	}
	
	public Memento createMemento(){
		return new Memento(this.state);
	}
	
	public void restoreMemento(Memento memento){
		setState(memento.getState());
	}
}

public class Memento {
	
	private String state = "";

	public Memento(String state){
		this.state = state;
	}
	
	public String getState(){
		return state;
	}
	
	public void setState(String state){
		this.state = state;
	}
	
}

public class Caretaker {

	private Memento memento;
	
	public Memento getMemento(){
		return memento;
	}
	
	public void setMemento(Memento memento){
		this.memento = memento;
	}
}

public class Client {

	public static void main(String[] args){
		Originator originator = new Originator();
		Caretaker caretaker = new Caretaker();
		caretaker.setMemento(originator.createMemento());
		originator.restoreMemento(caretaker.getMemento());
	}
}



扩展

clone方式的备忘录

类图:

技术分享


代码:

public class Originator implements Cloneable{

	private String state = "";
	
	private Originator backup;
	
	public String getState(){
		return state;
	}
	
	public void setState(String state){
		this.state  =state;
	}
	
	public void createMemento(){
		backup =  this.clone();
	}
	
	public void restoreMemento(){
		this.setState(backup.state);
	}
	
	@Override
	protected Originator clone(){
		try{
			return (Originator) super.clone();
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}


多种状态备忘录模式

实现思路:通过反射方式,将各个状态的getter和setter方法以及各个状态保存在map中,而Memento中存储这个map


更好的封装:

目的:防止备份被修改

类图:

技术分享



public class Originator {

	private String state = "";
	
	public String getState(){
		return state;
	}
	
	public void setState(String state){
		this.state  =state;
	}
	
	public Memento createMemento(){
		return new Memento(state);
	}
	
	public void restoreMemento(IMemento imemento){
		setState(((Memento) imemento).getState());
	}
	
	private class Memento implements IMemento{
		private String state = "";
		
		private Memento(String state){
			this.state = state;
		}
		
		private String getState(){
			return state;
		}
		
		private void setState(String state){
			this.state = state;
		}
	}
	
	
}



备忘录模式

标签:

原文地址:http://blog.csdn.net/renpengddxx/article/details/52143030

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!