定义
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
浅拷贝
先上代码:
定义一个Person类,实现Cloneable接口,重写clone()方法
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Person clone() {
Person p = null;
try {
p = (Person) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
客户端调用:
public class Client {
public static void main(String[] args) {
Person p1=new Person("小李",18);
Person p2 = p1.clone();
System.out.println(p1==p2);//false
System.out.println("p1:"+p1.toString());//p1:Person{name='小李', age=18}
System.out.println("p2:"+p2.toString());//p2:Person{name='小李', age=18}
}
}
输出与预想一致,拷贝成功!
再Person类中再加一个引用类型的成员变量Location,代码如下:
Person跟Location类:
public class Person implements Cloneable {
private String name;
private int age;
private Location location;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Person(String name, int age, Location location) {
this.name = name;
this.age = age;
this.location = location;
}
@Override
protected Person clone() {
Person p = null;
try {
p = (Person) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", location=" + location.toString() +
'}';
}
}
class Location{
private String loc;
private String room;
public Location(String loc, String room) {
this.loc = loc;
this.room = room;
}
@Override
public String toString() {
return "Location{" +
"loc='" + loc + '\'' +
", room='" + room + '\'' +
'}';
}
}
客户端:
public class Client {
public static void main(String[] args) {
Location location=new Location("bj","201");
Person p1=new Person("小李",18,location);
Person p2 = p1.clone();
System.out.println(p1==p2);
System.out.println("p1:"+p1.toString()+",location hashcode:"+p1.getLocation().hashCode());
System.out.println("p2:"+p2.toString()+",location hashcode:"+p2.getLocation().hashCode());
}
}
输出:
false
p1:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:460141958
p2:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:460141958
可以看出,location的hashcode值相等,说明是同一个对象,其实想想也对,Person复制对象的时候会把location属性也复制,但是复制的肯定是引用,复制的引用指向了原来的Location对象。
- 对于数据类型是基本数据(包括String)类型的成员变量,浅拷贝会直接进行值传递,也就是将该属性值复制一份给新的对象。
- 对于数据类型是引用数据类型的成员变量,比如说成员变量是某个数组、某个类的对象等,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例。在这种情况下,在一个对象中修改该成员变量会影响到另一个对象的该成员变量值
深拷贝
想要使得上述的Location对象也拷贝一份,然后Person对象的成员变量指向新的Location对象,就需要深拷贝。
方法也很简单,让Location也实现Cloneable接口,重新clone()方法,在Person clone() 中调用Location的clone() 即可,其实就是把每个对象都clone() 了一遍。
代码如下:
Person和Location类:
public class Person implements Cloneable {
private String name;
private int age;
private Location location;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Person(String name, int age, Location location) {
this.name = name;
this.age = age;
this.location = location;
}
@Override
protected Person clone() {
Person p = null;
try {
p = (Person) super.clone();
p.location=(Location) p.getLocation().clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", location=" + location.toString() +
'}';
}
}
class Location implements Cloneable{
private String loc;
private String room;
public Location(String loc, String room) {
this.loc = loc;
this.room = room;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return "Location{" +
"loc='" + loc + '\'' +
", room='" + room + '\'' +
'}';
}
}
Client:
public class Client {
public static void main(String[] args) {
Location location=new Location("bj","201");
Person p1=new Person("小李",18,location);
Person p2 = p1.clone();
System.out.println(p1==p2);
System.out.println("p1:"+p1.toString()+",location hashcode:"+p1.getLocation().hashCode());
System.out.println("p2:"+p2.toString()+",location hashcode:"+p2.getLocation().hashCode());
}
}
输出:
false
p1:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:460141958
p2:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:1163157884
深拷贝成功,但是如果Person对象特别复杂,其中有很多引用类型的成员变量,那就很麻烦。
还有一种深拷贝,序列化。
深拷贝(序列化)(推荐使用)
代码:
Persion和Location类:
public class Person implements Serializable {
private String name;
private int age;
private Location location;
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Person(String name, int age, Location location) {
this.name = name;
this.age = age;
this.location = location;
}
public Person deepClone() {
//创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this); //当前这个对象以对象流的方式输出
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
Person copyObj = (Person) ois.readObject();
return copyObj;
} catch (Exception e) {
return null;
} finally {
//关闭流
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (Exception e2) {
}
}
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", location=" + location.toString() +
'}';
}
}
class Location implements Serializable {
private String loc;
private String room;
public Location(String loc, String room) {
this.loc = loc;
this.room = room;
}
@Override
public String toString() {
return "Location{" +
"loc='" + loc + '\'' +
", room='" + room + '\'' +
'}';
}
}
Client:
public class Client {
public static void main(String[] args) {
Location location=new Location("bj","201");
Person p1=new Person("小李",18,location);
Person p2 = p1.deepClone();
System.out.println(p1==p2);
System.out.println("p1:"+p1.toString()+",location hashcode:"+p1.getLocation().hashCode());
System.out.println("p2:"+p2.toString()+",location hashcode:"+p2.getLocation().hashCode());
}
}
输出:
false
p1:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:325040804
p2:Person{name='小李', age=18, location=Location{loc='bj', room='201'}},location hashcode:1595428806
总结
- 创建新的对象比较复杂时,可以利用原型模式简化对象的创建过程,同时也能够提高效率,简单的对象new的效率比clone高。
- 不用重新初始化对象,而是动态地获得对象运行时的状态
- 如果原始对象发生变化(增加或者减少属性),其它克隆对象的也会发生相应的变化,无需修改代码
- 在实现深克隆的时候可能需要比较复杂的代码
- 缺点:需要为每一个类配备一个克隆方法,这对全新的类来说不是很难,但对已有的类进行改造时,需要修改其源代码,违背了 ocp 原则,这点请同学们注意.