2013-10-10 39 views
-1

這裏是下面的清單:克隆一個單音對象

 

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

爲什麼要做這個代碼拋出CloneNotSupportedException的?

+2

請正確格式化你的代碼。它的方式完全不可讀。另外,請使用適當的語言和/或框架標記問題。 –

回答

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 
0

如果你是克隆單獨的對象,那麼你違反了辛格爾頓的設計原則。

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