关于java:克隆一个Singleton对象

Clone a Singleton object

为什么这段代码会抛出克隆受支持感受?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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());
    }
}


如果你在克隆的Singleton对象你是违法的设计主的独生子。

城市clone违约保护的方法:protected native Object clone() throws CloneNotSupportedException冰;

如果你的Carextends,另一类是支持克隆,它是可能的两个violate设计原则的独生子。所以,正是绝对100%的某一单,真的是一个单身,我们必须添加一clone()方法和我们自己,把一CloneNotSupportedException如果任何人试图创造。下面是我们的重写Clone方法。

1
2
3
4
5
6
7
8
 @Override
    protected Object clone() throws CloneNotSupportedException {
        /*
         * Here forcibly throws the exception for preventing to be cloned
         */

        throw new CloneNotSupportedException();
        // return super.clone();
    }

请找到下面的两个代码块的工作为单件类克隆的克隆或避免uncommenting《城市法典。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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());
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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());

输出:

1
2
1481395006
2027946171