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

本文通过一个具体的案例,深入解析了备忘录模式在Java中的应用。从源发器类、备忘录类到负责人类的实现,展示了如何保存和恢复对象的状态,为读者提供了理解和运用备忘录模式的实践指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/**
 * 源发器类
 * @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());
		
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值