克隆单个音色对象
以下是清单:
public class Car { private static Car car = null; private void car() { } public static Car GetInstance() { if (car == null) { car = new Car(); } return car; } public static void main(String arg[]) throws CloneNotSupportedException { car = Car.GetInstance(); Car car1 = (Car) car.clone(); System.out.println(car.hashCode());// getting the hash code System.out.println(car1.hashCode()); } }
为什么这段代码会抛出cloneNotSupportedException?
public class Car implements Cloneable {
private static Car car = null;
public static Car GetInstance() {
if (car == null) {
car = new Car();
}
return car;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Car car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());
System.out.println(car1.hashCode());
输出:
1481395006
2027946171
如果你正在克隆单例对象,那么你违反了Singleton的设计原则。
默认情况下, clone
方法受到保护: protected native Object clone() throws CloneNotSupportedException
;
如果您的Car
扩展了另一个支持克隆的类,则可能违反单例的设计原则。 因此,为了绝对肯定单身人士确实是单身人士,我们必须添加我们自己的clone()
方法,并且如果有人尝试创建,则抛出CloneNotSupportedException
。 以下是我们的覆盖克隆方法。
@Override
protected Object clone() throws CloneNotSupportedException {
/*
* Here forcibly throws the exception for preventing to be cloned
*/
throw new CloneNotSupportedException();
// return super.clone();
}
请找到下面的代码块来克隆Singleton类,或者通过取消注释代码来避免克隆。
public class Car implements Cloneable {
private static Car car = null;
private void Car() {
}
public static Car GetInstance() {
if (car == null) {
synchronized (Car.class) {
if (car == null) {
car = new Car();
}
}
}
return car;
}
@Override
protected Object clone() throws CloneNotSupportedException {
/*
* Here forcibly throws the exception for preventing to be cloned
*/
// throw new CloneNotSupportedException();
return super.clone();
}
public static void main(String arg[]) throws CloneNotSupportedException {
car = Car.GetInstance();
Car car1 = (Car) car.clone();
System.out.println(car.hashCode());// getting the hash code
System.out.println(car1.hashCode());
}
}
链接地址: http://www.djcxy.com/p/49629.html