如果您正在克隆单例对象,那么您就违反了单例的设计原则。
默认clone
方法是受保护的protected native Object clone() throws CloneNotSupportedException
:
如果您Car
扩展了另一个支持克隆的类,则可能违反单例的设计原则。因此,要绝对 100% 肯定单例确实是单例,我们必须添加一个我们自己的方法,如果有人尝试创建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());
}
}