就克隆而言,副本的深度或浅度存在问题,因此知道克隆对象时会出现什么样的“危险”.我想我只使用过一次或两次clone(),那就是复制对象的当前状态,因为另一个线程(即访问Session中同一个对象的另一个HTTP请求)可能正在修改它.
编辑 – 我在下面做的评论更多的是问题:
但话说回来,你DID改变日期,所以这是你自己的错,因此整个讨论术语“防守”.如果在中小型开发人员组中,您自己控制的是所有应用程序代码,那么仅仅记录您的类是否足以作为制作对象副本的替代方法?或者这不是必需的,因为你应该总是假设在调用setter / getter时没有被复制的东西?
解决方法
You must program defensively with the assumption that clients of your class will do their best to destroy its invariants. This may actually be true if someone tries to break the security of your system,but more likely your class will have to cope with unexpected behavior resulting from honest mistakes on the part of the programmer using your API. Either way,it is worth taking the time to write classes that are robust in the face of ill-behaved clients.
Item 24: Make defensive copies when needed