为什么对象不应该是可复制的? [英] Why shouldn't an object be cloneable?

查看:111
本文介绍了为什么对象不应该是可复制的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多关于Object和Cloneable Interface的clone()方法的线程,但是我找不到我的问题的合理答案。
长话短说:

I read lots of threads about the clone() method of Object and the Cloneable Interface but I couldn't find a legitimate answer to my question. Long story short:

我想到的是Object有一个方法clone()可以神奇地克隆你的对象。但是,如果不实现Cloneable Interface,则无法使用该方法,因为此接口允许Object使用clone()方法。那他们为什么这样做呢?为什么不能从一开始就克隆每个对象?

What I figured out is that Object has a method clone() which can "magically" clone your object. But you can't use that method without implementing Cloneable Interface because this interface allows Object to use the clone() method. So why did they do that? Why shouldn't every object be cloneable from the start?

推荐答案

Cloneable对某些可变数据有意义。

Cloneable makes sense for some mutable data.

没有意义


  • 不可变数据

  • 您可能需要浅层或深层副本。

  • 表示线程,套接字,GUI组件等资源的对象

  • singleton和enumerated类型

  • 可变状态,其中只应复制数据以避免创建新对象。

  • immutable data
  • where you might need a shallow or a deep copy.
  • objects which represent resources such as threads, sockets, GUI components
  • singleton and enumerated types
  • mutable state where data should only be copied to avoid creating new objects.

一些编码样式建议将新的可变数据对象保持在最低限度。 Cloneable并不适合所有情况,如果你让所有对象Cloneable你将无法完全关闭它。

Some coding styles suggest keeping new mutable data object to a minimum. Cloneable doesn't suit all situations and if you made all objects Cloneable you wouldn't be able to turn it off cleanly.

注意:有许多项目避免使用可以在任何地方克隆。

Note: There are many projects which avoid using Cloneable anywhere.

这篇关于为什么对象不应该是可复制的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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