設計模式系列之建造者模式(Builder Pattern)——複雜物件的組裝與建立
By default this is not set. */ Builder headers(String... headers); /** * Build the RequestMappingInfo. */ RequestMappingInfo build(); } ``` `Builder`介面的預設實現,如下: ```java private static class DefaultBuilder implements Builder { private String[] paths = new String[0]; private RequestMethod[] methods = new RequestMethod[0]; private String[] params = new String[0]; private String[] headers = new String[0]; public DefaultBuilder(String... paths) { this.paths = paths; } @Override public Builder paths(String... paths) { this.paths = paths; return this; } @Override public DefaultBuilder methods(RequestMethod... methods) { this.methods = methods; return this; } @Override public DefaultBuilder params(String... params) { this.params = params; return this; } @Override public DefaultBuilder headers(String... headers) { this.headers = headers; return this; } @Override public RequestMappingInfo build() { ContentNegotiationManager manager = this.options.getContentNegotiationManager(); PatternsRequestCondition patternsCondition = new PatternsRequestCondition( this.paths, this.options.getUrlPathHelper(), this.options.getPathMatcher(), this.options.useSuffixPatternMatch(), this.options.useTrailingSlashMatch(), this.options.getFileExtensions()); return new RequestMappingInfo(this.mappingName, patternsCondition, new RequestMethodsRequestCondition(this.methods), new ParamsRequestCondition(this.params), new HeadersRequestCondition(this.headers), new ConsumesRequestCondition(this.consumes, this.headers), new ProducesRequestCondition(this.produces, this.headers, manager), this.customCondition); } } ``` `Spring`框架中許多`構建類`的例項化使用了類似上面方式,總結有以下特點: 1. `Builder`大多是`構建類`的內部類,`構建類`提供了一個靜態建立`Builder`的方法 2. `Builder`返回`構建類的例項`,大多通過`build()`方法 3. 構建過程有`大量引數`,除了幾個必要引數,使用者可根據自己所需選擇設定其他引數例項化物件 ## 模式總結 建造者模式的核心在於如何一步步構建一個包含多個組成部件的完整物件,使用相同的構建過程構建不同的產品,在軟體開發中,如果我們需要建立複雜物件並希望系統具備很好的靈活性和可擴充套件性可以考慮使用建造者模式。 `建造者模式`與`抽象工廠模式`有點相似,但是建造者模式返回一個完整的複雜產品,而抽象工廠模式返回一系列相關的產品;在抽象工廠模式中,客戶端通過選擇具體工廠來生成所需物件,而在建造者模式中,客戶端通過指定具體建造者型別並指導Director類如何去生成物件,側重於一步步構造一個複雜物件,然後將結果返回。**如果將抽象工廠模式看成一個汽車配件生產廠,生成不同型別的汽車配件,那麼建造者模式就是一個汽車組裝廠,通過對配件進行組裝返回一輛完整的汽車。** ### 主要優點 1. 將產品本身與產品的建立過程解耦,使得相同的建立過程可以建立不同的產品物件 2. 可以更加精細地控制產品的建立過程。將複雜產品的建立步驟分解在不同的方法中,使得建立過程更加清晰,也更方便使用程式來控制建立過程。 ### 適用場景 (1) 需要生成的產品物件有複雜的內部結構,這些產品物件通常包含多個成員屬性。 (2) 需要生成的產品物件的屬性相互依賴,需要指定其生成順序。 (3) 隔離複雜物件的建立和使用,並使得相同的建立過程可以建立不同的