建造者模式的扩展
模式擴展
建造者模式除了上面的用途外,在開發中還有一個常用的使用方式,
就是當一個類構造器需要傳入很多參數時,如果創建這個類的實例,代碼可讀性會非常差,而且很容易引入錯誤,
此時就可以利用建造者模式進行重構。
重構前代碼如下:
public class Phone {private String cpu;private String screen;private String memory;private String mainboard; ?public Phone(String cpu, String screen, String memory, String mainboard) {this.cpu = cpu;this.screen = screen;this.memory = memory;this.mainboard = mainboard;} ?public String getCpu() {return cpu;} ?public void setCpu(String cpu) {this.cpu = cpu;} ?public String getScreen() {return screen;} ?public void setScreen(String screen) {this.screen = screen;} ?public String getMemory() {return memory;} ?public void setMemory(String memory) {this.memory = memory;} ?public String getMainboard() {return mainboard;} ?public void setMainboard(String mainboard) {this.mainboard = mainboard;} ?@Overridepublic String toString() {return "Phone{" +"cpu='" + cpu + '\'' +", screen='" + screen + '\'' +", memory='" + memory + '\'' +", mainboard='" + mainboard + '\'' +'}';} } public class Client {public static void main(String[] args) {//構建Phone對象Phone phone = new Phone("intel","三星屏幕","金士頓","華碩");System.out.println(phone);} }上面在客戶端代碼中構建Phone對象,傳遞了四個參數,如果參數更多呢?
代碼的可讀性及使用的成本就是比較高。
重構后代碼:
Phone.java
package com.itheima.pattern.builder.demo2;/*** @version v1.0* @ClassName: Phone* @Description: 手機類* @Author: dym*/ public class Phone {private String cpu;private String screen;private String memory;private String mainboard;//私有構造方法private Phone(Builder builder) {this.cpu = builder.cpu;this.screen = builder.screen;this.memory = builder.memory;this.mainboard = builder.mainboard;}@Overridepublic String toString() {return "Phone{" +"cpu='" + cpu + '\'' +", screen='" + screen + '\'' +", memory='" + memory + '\'' +", mainboard='" + mainboard + '\'' +'}';}public static final class Builder {private String cpu;private String screen;private String memory;private String mainboard;public Builder cpu(String cpu) {this.cpu = cpu;return this;}public Builder screen(String screen) {this.screen = screen;return this;}public Builder memory(String memory) {this.memory = memory;return this;}public Builder mainboard(String mainboard) {this.mainboard = mainboard;return this;}//使用構建者創建Phone對象public Phone build() {return new Phone(this);}} }Client.java
package com.itheima.pattern.builder.demo2;/*** @version v1.0* @ClassName: Client* @Description: TODO(一句話描述該類的功能)* @Author: dym*/ public class Client {public static void main(String[] args) {//創建手機對象 通過構建者對象獲取手機對象Phone phone = new Phone.Builder().cpu("intel").screen("三星屏幕").memory("金士頓內存條").mainboard("華碩主板").build();System.out.println(phone);} }重構后的代碼在使用起來更方便,某種程度上也可以提高開發效率。
總結
- 上一篇: 原型模式——浅克隆和深克隆
- 下一篇: 创建者模式对比