如果你没有用Java克隆那么你做了什么以及你称之为什么? [英] If you don't clone in Java then what do you do and what do you call it?
问题描述
是否有人在Java中对复制构造函数/工厂方法等有任何建议或建立的最佳实践和命名约定?特别是,假设我有一个类 Thing
,我想要一个方法,返回一个具有相同值的新 Thing
作为 Thing
传入(或作为实例,如果它是实例方法)。你有这个作为构造函数或静态工厂方法或实例方法?你会怎么称呼它?
Does anyone have any suggested or established best practices and naming conventions for copy constructors / factory methods etc in Java? In particular, say I have a class Thing
and I want a method somewhere that returns a new Thing
with the same value as a Thing
passed in (or as the instance if it's an instance method). Would you have this as constructor or a static factory method or instance method? What would you call it?
根据标题,我想避免 clone()
和 Cloneable
。
As per the title, I want to avoid clone()
and Cloneable
.
推荐答案
Effective Java建议使用以下任一项:
Effective Java recommends either of the following:
-
复制构造函数(如其他人所述):
A copy constructor (as noted by others):
public Item(Item item) )
public Item(Item item)
复制工厂方法:
public static Item newInstance(Item item)
public static Item newInstance(Item item)
(此外,不会复制不可变数据)
(Also, no copying for immutables)
主要区别是#1你选择结果的实际类,而#2实现者可以返回一个子类。课程的语义可以指导你哪一个是最好的。
The primary difference is that with #1 you choose the actual class of the result, and with #2 the implementer can return a subclass. The semantics of the class may guide you into which one is best.
这篇关于如果你没有用Java克隆那么你做了什么以及你称之为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!