克隆与实例化新课程 [英] Cloning vs. Instantiating a new class
本文介绍了克隆与实例化新课程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这种情况下克隆良好做法吗?
Is cloning good practice in this case? How to do it better?
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中。尝试其他技术,例如Copy构造函数或Factory方法。
Cloning is rarely a good idea in Java. Try other techniques such as Copy constructors or Factory methods.
Wikipedia具有一篇不错的文章,说明为什么 clone()
在Java中有很多缺点。
Wikipedia has a nice article on why clone()
has many disadvantages in Java.
使用复制构造函数,创建一个将当前类的实例作为参数的构造函数,并复制本地类中的所有字段:
Using copy constructors, create a constructor that takes an instance of the current class as parameter, and copy all fields in the local class:
public class Foo {
private String bar;
private String baz;
public Foo(Foo other) {
this.bar = other.bar;
this.baz = other.baz;
}
}
使用工厂方法,创建方法将您的对象作为参数并返回包含相同值的对象:
Using factory methods, create a method that takes your object as parameter and return an object containing the same values:
public Foo copyFoo(Foo other) {
Foo foo = new Foo();
foo.setBar(other.getBar());
foo.setBaz(other.getBaz());
}
这篇关于克隆与实例化新课程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文