克隆与实例化新类

2024-04-20

在这种情况下,克隆是好的做法吗?怎样才能做得更好呢?

public ModelCollection startParsing() {

   return parseFeed(new ModelSpecialEntry); 
}

public ModelCollection parseFeed(ModelEntry pattern)  {

   ModelCollection modelCollection = new ModelCollection();

   while( condition ) {

     //TODO: Is cloning the best solution?
     ModelEntry model = (ModelEntry) pattern.clone();



     model.parse();

     //add this item to an collection
     modelCollection.add(model);


   }

   return modelCollection;
}

在 Java 中,克隆很少是一个好主意。尝试其他技术,例如复制构造函数或工厂方法。

维基百科有一篇好文章 http://en.wikipedia.org/wiki/Clone_%28Java_method%29 on why clone()Java有很多缺点。

使用复制构造函数,创建一个以当前类的实例作为参数的构造函数,并复制本地类中的所有字段:

public class Foo {

    private String bar;
    private String baz;

    public Foo(Foo other) {
        this.bar = other.bar;
        this.baz = other.baz;
    }

}

使用工厂方法,创建一个将对象作为参数并返回包含相同值的对象的方法:

public Foo copyFoo(Foo other) {
    Foo foo = new Foo();
    foo.setBar(other.getBar());
    foo.setBaz(other.getBaz());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

克隆与实例化新类 的相关文章

随机推荐