使用場景:
(1)類初始化需要消耗非常多的資源時哩都,通過拷貝可以避免一些消耗启绰;
(2)通過new對象需要非常繁瑣的數(shù)據(jù)準備或者訪問權(quán)限時;
(3)一個對象需要提供給其他對象訪問合砂,而且各個對象可能需要修改其值時目胡,可保護性拷貝(淺拷貝和深拷貝)
Class Diagram.png
private void test(){
address = new Address("gz","th","sp");
user = new User(10,"jack","18138780689",address);
Log.e(TAG,user.toString());
try {
userClone = user.clone();
Log.e(TAG,userClone.toString());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
userClone.address.city = "sz";
userClone.phoneNum = "18028512904";
Log.e(TAG,userClone.toString());
Log.e(TAG,user.toString());
}
'''
public class Address implements Cloneable{
public String city;
public String district;
public String street;
public Address(String city, String district, String street) {
this.city = city;
this.district = district;
this.street = street;
}
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", district='" + district + '\'' +
", street='" + street + '\'' +
'}';
}
@Override
protected Address clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
}
'''