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对象你是违法的设计主的独生子。
城市
如果你的
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 |