clone()vs copy constructor vs factory方法? [英] clone() vs copy constructor vs factory method?

查看:689
本文介绍了clone()vs copy constructor vs factory方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中实现了克隆()的快速谷歌,发现:
http://www.javapractices.com/topic/TopicAction.do?Id=71

I did a quick google on implementing clone() in Java and found: http://www.javapractices.com/topic/TopicAction.do?Id=71

它有以下评论:


复制构造函数和静态工厂方法提供了克隆的替代方法,并且更容易实现。

copy constructors and static factory methods provide an alternative to clone, and are much easier to implement.

我想做的就是做一个深层复制。实现clone()似乎很有意义,但这篇谷歌排名很高的文章让我有点害怕。

All I want to do is make a deep copy. Implementing clone() seems to make a lot of sense, but this highly google ranked article makes me a bit afraid.

以下是我注意到的问题:

Here are the issues that I've noticed:

这是一些无法编译的伪代码。

Here's some pseudo-code that won't compile.

public class MyClass<T>{
   ..
   public void copyData(T data){
       T copy=new T(data);//This isn't going to work.    
   }
   ..
}

示例1:使用复制泛型类中的构造函数。

Sample 1: Using a copy constructor in a generic class.

这很好有一个可重用代码的接口。

It's quite nice to have an interface for reusable code.

public class MyClass<T>{
    ..
    public void copyData(T data){
        T copy=data.clone();//Throws an exception if the input was not cloneable
    }
    ..
}

示例2:在泛型类中使用clone()。

Sample 2: Using clone() in a generic class.

我注意到克隆不是静态方法,但是不是仍然需要制作所有受保护字段的深层副本吗?在实现clone()时,在非可克隆子类中抛出异常的额外工作对我来说似乎微不足道。

I noticed that clone is not a static method, but wouldn't it still be necessary to make deep copies of all the protected fields? When implementing clone(), the extra effort to throw exceptions in non-cloneable subclasses seems trivial to me.

我错过了什么吗?任何见解都将不胜感激。

Am I missing something? Any insights would be appreciated.

推荐答案

基本上,克隆被破坏了。什么都不会轻易与泛型一起使用。如果你有这样的东西(缩短以得到重点):

Basically, clone is broken. Nothing will work with generics easily. If you have something like this (shortened to get the point across):

public class SomeClass<T extends Copyable> {


    public T copy(T object) {
        return (T) object.copy();
    }
}

interface Copyable {
    Copyable copy();
}

然后使用编译器警告您可以完成工作。因为泛型在运行时被擦除,所以执行复制的东西会在其中生成编译器警告生成强制转换。 在这种情况下无法避免。。在某些情况下可以避免(谢谢,kb304)但不是全部。考虑必须支持子类或实现接口的未知类的情况(例如,您正在迭代不一定生成相同类的可复制副本集合。)

Then with a compiler warning you can get the job done. Because generics are erased at runtime, something that does a copy is going to have a compiler warning generating cast in it. It is not avoidable in this case.. It is avoidable in some cases (thanks, kb304) but not in all. Consider the case where you have to support a subclass or an unknown class implementing the interface (such as you were iterating through a collection of copyables that didn't necessarily generate the same class).

这篇关于clone()vs copy constructor vs factory方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆