【发布时间】:2015-08-20 02:44:13
【问题描述】:
package main;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public final class Tutor {
private final String name;
private final Set<Student> tutees;
public Tutor(String name, Student[] students) {
this.name = name;
this.tutees = new HashSet<Student>();
for (int i = 0; i < students.length; i++) {
tutees.add(students[i]);
}
}
public Set<Student> getTutees() { return Collections.unmodifiableSet(tutees); }
public String getName() { return name; }
}
是否可以做更多的事情来使这个类不可变?字符串已经是不可变的,返回的集合是不可修改的。 tutees 和 name 变量是私有的和最终的。还能做什么?如果使用 Tutor 类的唯一类在包中,我可以将构造函数、getTutees 方法和 getName 方法更改为包私有吗?
编辑:
这是 Student 类,问题要求我描述必要的更改以使 Student 不可变。我已经注释掉了两个 setter 方法,所以我可以使变量成为最终的。这是使它真正不可变的唯一方法吗?
public final class Student {
private final String name;
private final String course;
public Student(String name, String course) {
this.name = name;
this.course = course;
}
public String getName() { return name; }
public String getCourse() { return course; }
//public void setName(String name) { this.name = name; }
//public void setCourse(String course) { this.course = course; }
}
【问题讨论】:
-
我认为您可能希望在代码审查中使用这个...
-
如果
Student不可变,则代码的调用者可以稍后对其进行修改。深拷贝数组。 -
对字符串的修改可能会导致创建新字符串,您可以使用最终的 StringBuffer。
-
制作包私有的东西与不变性无关。关于这一点:一个类要么是不可变的,要么是不可变的——中间没有。如果您查看您的代码,一旦创建了 Tutor 对象,就无法更改任何内容。但是,这并没有说明
Student对象,如果Student是可变的,它仍然可以通过getTutees()方法进行变异。 -
将构造函数设为私有并实现单例模式。
标签: java immutability mutable defensive-programming defensive-copy