复制构造函数通常应该复制实例变量,并在必要时进行一些深度状态 – 不保留对原始对象的引用.
你的吸气者&方法需要能够在对象自己的状态中操作,在它自己的变量中.在任何地方都有某种双路径结构,if语句要么是自己的变量,要么是从中复制的原始实例,设计很差,非常复杂/低效.
public class Board {
protected int size;
protected Cell[][] grid;
public Board (int N) {
this.size = N;
// for example, create a 2D array.
this.grid = new Cell[size][size];
}
public Board (Board orig) {
this.size = orig.size();
// deep-copy the grid.
this.grid = new Cell[size][];
for (int i = 0; i < size; i++) {
grid[i] = Arrays.copyOf( orig.grid[i], size);
}
}
public int size() {return size;}
}
我更喜欢受保护而不是私人,以获得更大的灵活性和更多功能.工程访问.
我也不使用字段前缀,而是使用此字符串消除字段分配(在setter或其他方法中).这种方法适用于简单字段.
对于集合,我将我的字段名称加上List或Map或者其他内容;参数的命名没有后缀.这使得多个操作和方法调用多个明确的调用.例如,add(List< Customer> customers)会将这些添加到字段customerList.