1. 建造者模式介紹
建造者模式是一種創建型設計模式,旨在通過將復雜對象的構建過程與其表示分離,使得同樣的構建過程可以創建不同的表示。它通常用于構造步驟固定但具體實現可能變化的對象。
1.1 功能:
- 封裝復雜對象的創建過程:適用于需要多個步驟來創建一個復雜對象的情況。
- 一個類中有些屬性屬于必填的,這些必填信息需在創建對象時做校驗;
- 有些屬性之間有依賴關系或約束條件,在創建對象時需對多個屬性做聯合約束校驗
- 提高代碼可讀性和可維護性:通過分離構建邏輯和表示邏輯,代碼更加清晰。
- 一個類中有很多屬性,使用構造函數,會導致參數列表過長,影響代碼的可讀性和易用性
- 支持不可變對象的創建:可以在對象構建完成后一次性設置所有屬性,避免部分初始化的狀態。
- 希望創建不可變對象,在對象在創建好之后,就不能再修改內部的屬性值
1.2 用法:
step1. 目標類提供一個私有構造函數,只能通過 Builder 來實例化。
step2. 定義一個 Builder 類負責構建目標對象,屬性與目標類一致,逐步設置各個參數。
2. 代碼演示
場景說明:新建一個 Computer對象,要求:
- 其 cpu、ram、storage屬性是必有的
- storage值不能小于0,默認值為1024;
- name和code屬性可空,但不能同時為空。
Computer比較符合建造者模式使用條件,對應代碼如下:
public class Computer {private String cpu;private String ram;private Long storage;private String name;private String code;//目標類私有構造函數,必須使用Builder來創建目標類對象private Computer(Builder builder) {this.cpu = builder.cpu;this.ram = builder.ram;this.storage = builder.storage;this.name = builder.name;this.code = builder.code;}public static class Builder {//Builder屬性與目標類Computer屬性一致private String cpu;private String ram;private Long storage = 1024L; // 默認值private String name;private String code;//設置屬性時,做相關校驗public Builder setCpu(String cpu) {if (cpu == null || cpu.isEmpty()) {throw new IllegalArgumentException("CPU cannot be null or empty");}this.cpu = cpu;return this;}public Builder setRam(String ram) {if (ram == null || ram.isEmpty()) {throw new IllegalArgumentException("RAM cannot be null or empty");}this.ram = ram;return this;}public Builder setStorage(Long storage) {if (storage == null || storage <= 0) {throw new IllegalArgumentException("Storage must be greater than 0");}this.storage = storage;return this;}public Builder setName(String name) {this.name = name;return this;}public Builder setCode(String code) {this.code = code;return this;}public Computer build() {// 創建Computer對象前,做相關校驗if (this.cpu == null || this.cpu.isEmpty()) {throw new IllegalStateException("CPU is not set");}if (this.ram == null || this.ram.isEmpty()) {throw new IllegalStateException("RAM is not set");}if (this.storage == null || this.storage <= 0) {throw new IllegalStateException("Storage is not valid");}if ((this.name == null || this.name.isEmpty()) && (this.code == null || this.code.isEmpty())) {throw new IllegalStateException("Both name and code cannot be empty");}return new Computer(this);}}@Overridepublic String toString() {return "Computer{" +"code='" + code + '\'' +", name='" + name + '\'' +", cpu='" + cpu + '\'' +", ram='" + ram + '\'' +", storage=" + storage +'}';}
}
使用Demo如下:
public class BuilderDemo {public static void main(String[] args) {// 使用 Builder 構建一個 Computer 對象Computer computer = new Computer.Builder().setCpu("Intel i9").setRam("32GB").setStorage("1024L").setName("MacBook Pro").setCode("123456").build();// 打印結果System.out.println(computer);}
}