大话设计模式之原型模式

原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。


原型模式其实就是从一个对象再创建另外一个可以定制的对象,而且不需要知道任何创建的细节。


一般在初始化的信息不发生变化的情况下,克隆是最好的办法。这既隐藏了对象创建的细节,又对性能是大大的提高。不用重新初始化对象,而是动态地获得对象运行时的状态。

package Prototype;

public class MainClass {

	/**
	 * @param args
	 * @throws CloneNotSupportedException 
	 */
	public static void main(String[] args) throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		Resume a = new Resume("big bird");
		a.SetPersonalInfo("man", "29");
		a.SetWorkExperience("1988-2000", "IBM");
		
		Resume b = (Resume)(a.clone());
//		if (a.getAge().equals(b.getAge())) {
//			System.out.println("a\'s age equals b\'s age");
//		}
//		
//		if (a.getAge() == b.getAge()) {
//			System.out.println("a\'s age == b\'s age");
//		}
		
		b.SetWorkExperience("1998-2006", "emc");
		
		a.Display();
		b.Display();
	}

}

class Resume implements Cloneable {
	private String name;
	private String sex;
	private String age;
	private String timeArea;
	private String company;
	
	
	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the sex
	 */
	public String getSex() {
		return sex;
	}

	/**
	 * @param sex the sex to set
	 */
	public void setSex(String sex) {
		this.sex = sex;
	}

	/**
	 * @return the age
	 */
	public String getAge() {
		return age;
	}

	/**
	 * @param age the age to set
	 */
	public void setAge(String age) {
		this.age = age;
	}

	/**
	 * @return the timeArea
	 */
	public String getTimeArea() {
		return timeArea;
	}

	/**
	 * @param timeArea the timeArea to set
	 */
	public void setTimeArea(String timeArea) {
		this.timeArea = timeArea;
	}

	/**
	 * @return the company
	 */
	public String getCompany() {
		return company;
	}

	/**
	 * @param company the company to set
	 */
	public void setCompany(String company) {
		this.company = company;
	}

	public Resume(String name) {
		this.name = name;
	}
	
	public void SetPersonalInfo(String sex, String age) {
		this.sex = sex;
		this.age = age;
	}
	
	public void SetWorkExperience(String timeArea, String company) {
		this.timeArea = timeArea;
		this.company = company;
	}
	
	public void Display() {
		System.out.println(this.name+" "+this.sex+" "+this.age);
		System.out.println("工作经历:"+timeArea+" "+company);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#clone()
	 */
	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
}
以上代码执行的是浅复制。

深复制需要特殊处理,为Resume定义一个私有的构造方法。在clone()中调用私有构造方法,重新赋值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值