0

是否可以克隆单音类的对象?请看下面的例子

public class Car implements Cloneable{
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());//printing the hash code
System.out.println(car1.hashCode());}
public Car clone(){
return car;}
}
4

2 回答 2

0

当然可以,但不要那样做。 确实,如果您需要破坏 Singleton 对象的目的,则表示需要重构您的类以及如何访问它。

于 2013-10-10T10:21:29.573 回答
-1

您可以通过这种方式克隆您的类以获得所需的行为。

public Car clone() {
    Car c = null;
    try {
        c = (Car) super.clone();
        return c;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
        throw new RuntimeException();
    }
}
于 2013-10-10T10:18:05.293 回答