public class Student {
public Student(String name){
do_smth(name);
}
public Student(){
this("Mike");
}
}
如何强制开发人员仅在值与默认值不同时使用参数化构造函数:不调用new Student("Mike")而是使用for this new Student()?
原因:我们有5个形参的构造函数。在大多数情况下,参数是相同的。但也有大约5%-10%的情况是不同的。所以为了避免重复,我想使用这样的方法。我知道在这里使用类似Builder的模式可能会更好。但我不喜欢冗长。
这可以通过使用带有标志的额外私有构造函数来实现:
public class Student {
public Student(String name) {
this(name, false);
}
public Student() {
this("Mike", true);
}
private Student(String name, boolean defaultUsed) {
if (!defaultUsed && "Mike".equals(name)) {
throw new IllegalArgumentException(
"Tut-tut lil kid, it's pwohibited to set Mike's name outside defauwt constwuctor");
}
do_smth(name); // only if do_smth cannot be overridden in child classes
}
}
注意:方法do_smth
应该是private
或final
,这样它就不能在子类中重载,这比限制从特定构造函数设置名称要重要得多。