シングルトン オブジェクトのクローンを作成している場合は、シングルトンの設計原則に違反しています。
デフォルトの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());
}
}