Builder模式是一步一步建立一個複雜對象的建立型模式。該模式將構建複雜對象的過程和它的部件解耦,使得構建過程和部件的表示隔離開來。java
本節側重變種Builder模式,示例代碼以下:設計模式
public class RobustPerson { // 必要參數 private final int id; // 全部屬性都被final修飾 private final String name; // 可選參數 private final int age; private final String gender; private final double height; private final int weight; private RobustPerson(Builder builder) { // 構造方法私有,即客戶端不能直接建立RobustPerson對象 this.id = builder.id; this.name = builder.name; this.age = builder.age; this.gender = builder.gender; this.height = builder.height; this.weight = builder.weight; } public static final class Builder { // 必要參數 private final int id; // 必要屬性被final修飾 private final String name; // 可選參數 private int age; private String gender; private double height; private int weight; public Builder(int id, String name) { this.id = id; this.name = name; } // 必要參數經過構造方法賦值 public Builder age(int age) { this.age = age; return this; } // 可選參數經過同名方法賦值 public Builder gender(String gender) { this.gender = gender; return this; } public Builder height(double height) { this.height = height; return this; } public Builder weight(int weight) { this.weight = weight; return this; } public RobustPerson build() { RobustPerson person = new RobustPerson(this); // 複雜業務語義校驗,對於校驗不經過場景,拋出異常 if (person.height != 0 && person.weight != 0) { // Builder對象並不是線程安全的,不能用this.xxx校驗 double bmi = person.weight / (person.height * person.height); if (bmi < 18 || bmi > 25) { // 身體質量指數(BMI)低於18或高於25時表示不健康 throw new IllegalArgumentException(person.name+" NOT A ROBUST PERSON!"); } } return person; } } public Builder toBuilder() { // 克隆 return new Builder(this.id, this.name).age(this.age) .gender(this.gender).height(this.height).weight(this.weight); } @Override public String toString() { return name + "{" + "id=" + id + ", age=" + age + ", gender='" + gender + '\'' + ", height=" + height + "m, weight=" + weight + "kg}"; } }
測試類以下:安全
public class BuilderTest { public static void main(String[] args) { RobustPerson jack = new RobustPerson.Builder(1, "Jack") .age(18).gender("male").height(1.70).weight(65).build(); System.out.println(jack); System.out.println("Jack keeps eating too much..."); System.out.println(jack.toBuilder().weight(80).build()); } }
運行後輸出:ide
Jack{id=1, age=18, gender='male', height=1.7m, weight=65kg} Jack keeps eating too much... Exception in thread "main" java.lang.IllegalArgumentException: Jack NOT A ROBUST PERSON! at builder.RobustPerson$Builder.build(RobustPerson.java:48) at builder.BuilderTest.main(BuilderTest.java:14)
結合上節示例代碼,可知Builder模式建立對象具備如下特色:函數
但Builder模式也不可避免地存在自身的缺點。例如:測試