您的位置:首页 > 其它

原型模式

2016-01-07 22:14 267 查看








package prototype;

import java.util.Date;

/**
* 羊
*
* @author zhangjianbin
*
*/
public class Sheep2 implements Cloneable {

private String name;
private Date birthdays;

public Sheep2() {
super();
}

public Sheep2(String name, Date birthdays) {
super();
this.name = name;
this.birthdays = birthdays;
}

public String getName() {
return name;
}

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

public Date getBirthdays() {
return birthdays;
}

public void setBirthdays(Date birthdays) {
this.birthdays = birthdays;
}

/**
* 让该类俱有克隆功能 深克隆
*  通过对象序列化 和反序列化也可以实现深克隆
*/
@Override
protected Object clone() throws CloneNotSupportedException {
Object obj = super.clone();
Sheep2 s = (Sheep2) obj;
s.birthdays = (Date) this.birthdays.clone(); // 克隆属性对象 ,实现深克隆
return obj;
}

}


package prototype;

import java.util.Date;

/**
* 羊
*
* @author zhangjianbin
*
*/
public class Sheep implements Cloneable {

private String name;
private Date birthdays;

public Sheep() {
super();
}

public Sheep(String name, Date birthdays) {
super();
this.name = name;
this.birthdays = birthdays;
}

public String getName() {
return name;
}

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

public Date getBirthdays() {
return birthdays;
}

public void setBirthdays(Date birthdays) {
this.birthdays = birthdays;
}

/**
* 让该类俱有克隆功能 (浅克隆)
*/
@Override
protected Object clone() throws CloneNotSupportedException {
Object obj = super.clone();
return obj;
}

}


public static void main(String[] args) throws CloneNotSupportedException {
// 浅克隆
shallowClone();

// 深克隆
deepClone();

}

private static void deepClone() throws CloneNotSupportedException {
Date date = new Date();

Sheep2 s1 = new Sheep2("羊", date);

/**
* 浅克隆对象 俱有相同的属性,也引用相同的对象地址
*/
Sheep2 s2 = (Sheep2) s1.clone();

System.err.println(s1.getBirthdays());

date.setTime(1212121212L);

System.err.println(s2.getBirthdays());
}

private static void shallowClone() throws CloneNotSupportedException {
Date date = new Date();

Sheep s1 = new Sheep("羊", date);

/**
* 浅克隆对象 俱有相同的属性,也引用相同的对象地址
*/
Sheep s2 = (Sheep) s1.clone();

System.err.println(s1.getBirthdays());

date.setTime(1212121212L);

System.err.println(s2.getBirthdays());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: