例如java
void method(String p1, int p2, bool p3=false);
复制代码
Java不支持这种特性, 若是你真的有需求,你能够git
这个很简单github
void method(String p1, int p2, bool p3){
// ....
};
void method(String p1, int p2){
bool p3 = false;
// ...
};
复制代码
这样就至关于给p3一个默认的参数值。安全
可是有的时候若是参数太多,就不适合了。 就要用到下面的工厂方法bash
public class StudentBuilder {
private String _name;
private int _age = 14; // this has a default
private String _motto = ""; // most students don't have one
public StudentBuilder() { }
public Student buildStudent() {
return new Student(_name, _age, _motto);
}
public StudentBuilder name(String _name) {
this._name = _name;
return this;
}
public StudentBuilder age(int _age) {
this._age = _age;
return this;
}
public StudentBuilder motto(String _motto) {
this._motto = _motto;
return this;
}
}
复制代码
Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
.name("Spicoli")
.age(16)
.motto("Aloha, Mr Hand")
.buildStudent();
复制代码
在上面的示例中,咱们没有直接 的建立一个Student对象,而是 经过StudentBuilder来建立一个工厂, 而后在这个工厂中预先设定了一些模板,ui
而不是直接这样写:this
Student s1 = new Student().age(16)
复制代码
这样写有两个坏处spa
.age()
方法,这个方法可能会被滥用。收录于 github.com/fish56/Java…code