-1

このコードが CloneNotSupportedException をスローするのはなぜですか?

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());
    }
}
4

2 に答える 2

2

シングルトン オブジェクトのクローンを作成している場合は、シングルトンの設計原則に違反しています。

デフォルトの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());
    }
}    
于 2016-06-22T08:01:03.510 に答える
0
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
于 2013-10-10T09:35:54.077 に答える