允許函式在沒有傳入值的情況下,以指定的預設值初始化。
public class Person{
private String name;
private int age;
private int gender;
public Person(String name, int age, int gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public Person(int age, int gender){
this.name = "noName"; // 預設參數
this.age = age;
this.gender = gender
}
}
透過介面定義一個創建的過程,將物件的建構過程隱藏
* 使用情境: 當傳入的物件較為複雜時, 分離創建步驟, 使創建過程更清晰 (請自行搜尋, 本篇不討論)
public class Person{
...
public Person(String name, int age, int gender){
...
}
}
public interface Builder{ //以介面分離
void setName(String name);
void setAge(int age);
void setGender(int gender);
void Person create();
}
public class concreteBuilder implements Builder{
// 實作介面方法
}
public class Person{
...
private Person(String name, int age, int gender){
// 將建構子存取權限設為私有, 讓使用者無法直接創建
...
}
public static class Builder{
// 透過靜態Builder 物件創建物件
private String name;
private int age;
private int gender;
public Builder(){
// 不需參數即可創建 (使用預設值)
this.name = "Diane";
this.age = 18;
this.gender = 2;
}
public Builder setName(String name){
// 開放方法讓使用者可以選擇性輸入
this.name = name;
return this;
}
....
public Person creat(){
// 必須透過Builder呼叫才可以創建物件
retrun new Person(name,age,int);
}
}
}
public class Main {
public static void main(String[] args){
Person person = new Person.Builder().setName("Tina").create();
Person person2 = new Person.Builder().create();
System.out.println(person.getName()); //Tina
System.out.println(person2.getName()); //Diane
}
}