23种设计模式之备忘录模式

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码实现:

/**
 * 源发器类
 * @author 万河归海
 *
 */
public class Emp {
	private String name;
	private int age;
	private double salary;
	//进行备忘操作,并返回备忘录对象
	public EmpMemento memento(){
		return new EmpMemento(this);
	}
	//进行数据恢复,恢复成备忘录对象的值
	public void recovery(EmpMemento mmt){
		this.name = mmt.getName();
		this.age = mmt.getAge();
		this.salary = mmt.getSalary();
	}
	public Emp(String name, int age, double salary) {
		super();
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	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 class EmpMemento {
	private String name;
	private int age;
	private double salary;
	public EmpMemento() {
		
	}
	public EmpMemento(Emp emp) {
		super();
		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;
	}
	
}

/**
 * 负责人类
 * 负责管理备忘录对象
 * @author 万河归海
 *
 */
public class CareTaker {
	private EmpMemento emp;
//	private List<EmpMemento> list = new ArrayList<EmpMemento>();
	public EmpMemento getEmp() {
		return emp;
	}

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

public class Test {
	public static void main(String[] args) {
		CareTaker care = new CareTaker();
		
		Emp emp = new Emp("小明",15,6920);
		System.out.println("第一次打印对象信息:姓名-"+emp.getName()+"----年龄-"+emp.getAge()+"----工资-"+emp.getSalary());
		//备忘一次
		care.setEmp(emp.memento());
		emp.setAge(45);
		emp.setSalary(600);
		System.out.println("第二次打印对象信息:姓名-"+emp.getName()+"----年龄-"+emp.getAge()+"----工资-"+emp.getSalary());
		
		//恢复信息
		emp.recovery(care.getEmp());
		System.out.println("第三次打印对象信息:姓名-"+emp.getName()+"----年龄-"+emp.getAge()+"----工资-"+emp.getSalary());
		
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/JW614718/article/details/90035616
今日推荐