备忘录模式





package memento;
/***
 * 源发器
 * @author zw
 *
 */
public class Emp {
	private String name;
	private int age;
	private double salary;
	
	//进行备忘录操作,并且返回备忘录对象
	public EmpMemento memento() {
		return new EmpMemento(this);
	}
	
	//从备忘录恢复数据
	public void recovery(EmpMemento emp) {
		this.name = emp.getName();
		this.age = emp.getAge();
		this.salary  = emp.getSalary();
	}
	
	
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public Emp(String name, int age, double salary) {
		super();
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	
	
}

package memento;
/***
 * 备忘录类
 * @author zw
 *
 */
public class EmpMemento {
	private String name;
	private int age;
	private double salary;
	
	
	//存储到备忘录下
	public EmpMemento(Emp e) {
		this.name = e.getName();
		this.age = e.getAge();
		this.salary = e.getSalary();
	}
	
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	
}
package memento;
/**
 * 负责人
 * 负责管理备忘录对象
 * @author zw
 *
 */
public class CarTaker {
	
	private EmpMemento emp;

	public EmpMemento getEmp() {
		return emp;
	}

	public void setEmp(EmpMemento emp) {
		this.emp = emp;
	}
	
}


package memento;

public class Client {
	public static void main(String[] args) {
		CarTaker ct = new CarTaker();
		
		Emp emp = new Emp("javazhangwei",18, 5000000);
		System.out.println("第一次打印:"+emp.getName()+"---"+emp.getAge()+"---"+emp.getSalary());
		
		ct.setEmp(emp.memento());
		
		emp.setAge(19);
		emp.setName("张伟");
		emp.setSalary(10000000);
		System.out.println("第二次打印:"+emp.getName()+"---"+emp.getAge()+"---"+emp.getSalary());
		
		emp.recovery(ct.getEmp());//恢复备忘录
		System.out.println("第三 次打印:"+emp.getName()+"---"+emp.getAge()+"---"+emp.getSalary());
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值