如果你是克隆單獨的對象,那麼你違反了辛格爾頓的設計原則。
默認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());
}
}
請正確格式化你的代碼。它的方式完全不可讀。另外,請使用適當的語言和/或框架標記問題。 –