克隆与实例化新类
在这种情况下,克隆是好的做法吗?怎样才能做得更好呢?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Java 中,克隆很少是一个好主意。尝试其他技术,例如复制构造函数或工厂方法。
维基百科有一篇不错的文章介绍了为什么
clone()
Java有很多缺点。使用复制构造函数,创建一个将当前类的实例作为参数的构造函数,并复制本地类中的所有字段:
使用工厂方法,创建一个将对象作为参数的方法,并返回一个包含相同值的对象:
Cloning is rarely a good idea in Java. Try other techniques such as Copy constructors or Factory methods.
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:
Using factory methods, create a method that takes your object as parameter and return an object containing the same values:
您可以使用复制构造函数而不是实现
可克隆
,但看起来您有一个ModelEntry
类的层次结构,因此使用clone
可能是最好的方法。请参阅此问题,了解有关Cloneable
You could use a copy constructor instead of implementing
Cloneable
, but it looks like you have a hierarchy ofModelEntry
classes, so usingclone
may be the best approach. See this question for some pointers on whats wrong withCloneable
我认为,这就像编程中的其他一切一样:它取决于对象规范。
尝试做一个非常快速的测试:
克隆 100000 个对象并实例化相同数量的对象并检查需要多长时间 (System.currentTimeInMilis())。通常克隆速度更快。
请记住,克隆有一个问题 - 添加新字段等时,您也需要修改 clone() 方法。
I thing, that it is like with everything else in programming: it depends on the object specyfication.
Try to make a really quick test:
clone 100000 objects and instantiates the same amount of objects and check time how long it takes (System.currentTimeInMilis()). Often clone is faster.
And remember that with clone there is one problem - when adding new field etc. you need to modify clone() method too.
许多程序员都同意,克隆并不是一个好主意。
这是很容易出错的。您必须小心地重写
clone()
。忘记调用super.clone()
是一个常见的错误。Clone is not a good idea as many programmers agree.
It's error-prone. You have to override
clone()
carefully.Forgetting invokingsuper.clone()
is a popular bug.