我正在学习对象深度克隆,我有一个带有 getInstance 方法的员工类,它返回一个单例,我正在克隆返回的对象。下面是类和测试类。
public class Employee implements Serializable , Cloneable {
public static Employee employee;
private String name;
private int age;
private Employee(){
}
public Employee(String name, int age) {
super();
this.name = name;
this.age = age;
}
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static Employee getInstance(){
if(employee == null ){
employee = new Employee();
return employee;
}
return employee;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
对象深拷贝测试类
public class CopyTest {
/**
* @param args
*/
public static void main(String[] args) {
try {
Employee original = Employee.getInstance();
original.setName("John");
original.setAge(25);
Employee cloned = (Employee)copy(original);
System.out.println("Original -->"+Employee.getInstance().getName());
cloned.getInstance().setName("Mark");
System.out.println("Cloned -->"+cloned.getInstance().getName());
System.out.println("Original -->"+Employee.getInstance().getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Object copy(Object orig) {
Object obj = null;
try {
// Write the object out to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(orig);
out.flush();
out.close();
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return obj;
}
}
输出
Original -->John
Cloned -->Mark
Original -->Mark
问题
尽管我克隆了原始对象以创建它的副本,
Employee cloned = (Employee)copy(original);
我通过调用修改克隆对象的属性
cloned.getInstance().setName("Mark");
正如您从控制台输出中看到的那样,它反映到原始对象。我认为这是因为静态调用?,我该如何克服呢?我是否违反了通过 getInstance 方法需要对象的单个实例的原则,然后我决定稍后制作该对象的副本。