定义:拷贝原型创建新的对象;
对象克隆-程序更高的效率和扩展性;
对象调用Object的clone方法,必须实现Cloneable接口,默认是浅拷贝;概念:
浅拷贝-值类型拷贝和引用拷贝,引用的具体对象不拷贝,Object的clone方法;
深拷贝-实现引用对象的拷贝、可以使用1.重写clone方法,引用属性逐个拷贝或 2.对象的序列化和反序列化实现(简单、常用);
UML类图:
代码实现:
/**
* 原型模式(克隆模式)
*
*/
class Address implements Serializable {
public String city;
public String country;
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", country='" + country + '\'' +
'}';
}
}
class User implements Cloneable, Serializable {
//引用类型
public String name;
//引用对象
public Address address;
public User(String name, Address address) {
this.name = name;
this.address = address;
}
/**
* 浅拷贝:利用Object的clone方法克隆对象
*
* @return 拷贝的对象
*/
protected User shallowClone() {
User userClone = null;
try {
//调用Object的clone方法
userClone = (User) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return userClone;
}
/**
* 深拷贝:利用对象的序列化与反序列化
*
* @return
*/
protected User deepClone() {
User userClone = null;
// 将对象写到流里
ByteArrayOutputStream bo = null;
ObjectOutputStream oo = null;
// 从流里读出来
ByteArrayInputStream bi = null;
ObjectInputStream oi = null;
try {
// 将对象写到流里
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 从流里读出来
bi = new ByteArrayInputStream(bo.toByteArray());
oi = new ObjectInputStream(bi);
userClone = (User) oi.readObject();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
} finally {
//关闭资源
if (oi != null) {
try {
oi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bi != null) {
try {
bi.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oo != null) {
try {
oo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bo != null) {
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return userClone;
}
/**
* 重写Object的clone方法
*
* @return
*/
@Override
protected User clone() {
//深拷贝
// return deepClone();
//浅拷贝
return shallowClone();
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", address=" + address +
'}';
}
}
/**
* 对象拷贝测试
*/
public class MyClone {
public static void main(String[] args) {
User user = new User("张三", new Address());
//对象克隆
User user2 = user.clone();
//验证深拷贝/浅拷贝
user2.address.city = "深圳";
System.out.println(user);
System.out.println(user2);
System.out.println(user == user2);
System.out.println(user.name == user2.name);
System.out.println(user.address == user2.address);
}
}