原型模式

当你需要一个对象的原型的时候(复制),这时候你可以会需要用到原型模式

一、在去公司面试的时候,你肯定需要简历,你可能会把一份简历复印多份,用代码描述下简历复印的过程

简历类:

public class Resume{
	
	private String name;
	
	private String sex;
	
	private WorkTime workTime;
	
	public Resume() {
		workTime=new WorkTime();
	}
	
	private Resume(WorkTime workTime) throws CloneNotSupportedException {
		this.workTime=(WorkTime) workTime.clone();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}
	
	public void setTime(String time) {
		this.workTime.setTime(time);
	}
	
	public String getTime() {
		return this.workTime.getTime();
	}
	
	public void setCompany(String company) {
		this.workTime.setCompany(company);
	}
	
	public String getCompany(String company) {
		return this.workTime.getCompany();
	}
	
	@Override
	protected Object clone() throws CloneNotSupportedException {
		Resume resume=new Resume(this.workTime);
		resume.setName(this.name);
		resume.setSex(this.sex);
		return resume;
	}
	
	public void display() {
		System.out.println("姓名:"+ this.name);
		System.out.println("性别:"+this.sex);
		System.out.println("在"+this.workTime.getCompany()+"工作"+this.workTime.getTime());
	}
}

WorkTime类

public class WorkTime {
	
	private String time;
	
	private String company;

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}
	@Override
	protected Object clone() throws CloneNotSupportedException {
		WorkTime workTime=new WorkTime();
		workTime.setCompany(this.company);
		workTime.setTime(this.time);
		return workTime;
	}
}

测试类:

public class Test {
	public static void main(String[] args) throws CloneNotSupportedException {
		Resume resume=new Resume();
		resume.setName("小明");
		resume.setSex("男");
		resume.setTime("2年");
		resume.setCompany("xx");
		
		Resume resumeClone=(Resume) resume.clone();
		resumeClone.setName("小王");
		resumeClone.setCompany("餐馆");
		
		resume.display();
		resumeClone.display();
	}
}

输出结果:

这里涉及到一个比较重要的点就是深拷贝和浅拷贝的问题,如果父类里面含有对象的引用,那么如果不是用深拷贝的话,当修改小王的workTime时候,就也会修改小明的。所以均需要重写clone方法,重新生成一个对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值