备忘录模式

个人感觉备忘录模式有些像系统备份的概念。比如说你将系统按时间点备份几个版本。如果哪天你系统出问题了也不用怕,把之前备份还原下就好。

写下代码描述上面情景:

package com.lyy.pattern.memorandum;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统
 * @author ThinkPad
 *
 */
public class WinSystem {
	
	List<String> data = new ArrayList<String>();
	
	public WinSystem() {
		data.add("1");
		data.add("2");
	}

	/**
	 * 读获取所有数据到GhoFile文件中(创建备份)
	 * @return
	 */
	public GhoFile ReadData2GhoFile(int version) {
		return new GhoFile(data , version);
	}

	public void restore(GhoFile ghoFile) {
		this.data = ghoFile.getData();
	}
	
	/**
	 * 写入内容
	 * @param content
	 */
	public void write(String content) {
		data.add(content);
	}

	@Override
	public String toString() {
		return "WinSystem [data=" + data + "]";
	}

	
}

package com.lyy.pattern.memorandum;

import java.util.HashMap;
import java.util.Map;

/**
 * 一键备份软件
 * @author ThinkPad
 *
 */
public class Ghost {

	private Map<Integer, GhoFile> ghoFileMap = new HashMap<Integer, GhoFile>();
	
	
	/**
	 * 备份
	 * @param system
	 */
	public void backup(WinSystem system, int version) {
		GhoFile file = system.ReadData2GhoFile(version);
		ghoFileMap.put(version, file);
	}
	
	
	
	/**
	 * 还原
	 * @param system
	 * @param date
	 */
	public void restore(WinSystem system, int version) {
		GhoFile ghoFile = ghoFileMap.get(version);
		system.restore(ghoFile);
	}
	
}

package com.lyy.pattern.memorandum;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Ghost备份的文件
 * @author ThinkPad
 *
 */
public class GhoFile {

	/**
	 * 文件内容
	 */
	private List<String> data;
	
	private int version;
	
	public GhoFile(List<String> data, int version) {
		this.data = new ArrayList<String>(data);
		this.version = version;
	}

	public List<String> getData() {
		return data;
	}

	@Override
	public String toString() {
		return "GhoFile [data=" + data + ", version=" + version + "]";
	}


	
	
	
	
}

package com.lyy.pattern.memorandum;

public class Main {

	public static void main(String[] args) {
		Ghost ghost = new Ghost();
		WinSystem system = new WinSystem();
		//备份
		ghost.backup(system, 1);
		System.out.println("备份后系统情况: "+system);
		//向系统写入新内容
		system.write("3");
		System.out.println("写入新内容系统情况: "+system);
		//还原
		ghost.restore(system, 1);
		System.out.println("返原到版本1后系统情况: "+system);
		
	}
}
输出情况:
备份后系统情况: WinSystem [data=[1, 2]]
写入新内容系统情况: WinSystem [data=[1, 2, 3]]
返原到版本1后系统情况: WinSystem [data=[1, 2]]

给张类图理直观些:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值