設計模式—建造者模式(Builder)
阿新 • • 發佈:2020-03-28
title: 設計模式—建造者模式
建造者模式(Builder)是一步一步建立一個複雜的物件,它允許使用者只通過指定複雜物件的型別和內容就可以構建它們,使用者不需要知道內部的具體構建細節。建造者模式屬於物件建立型模式。我們獲得一個物件的時候不是直接new這個物件出來,而是對其建造者進行屬性設定,然後建造者在根據設定建造出各個物件出來。建造者模式又可以稱為生成器模式。
模式結構
一個標準的建造者模式包含如下角色:
- Builder:抽象建造者
- ConcreteBuilder:具體建造者
- Director:指揮者
- Product:產品角色
原始碼導讀
建造者模式使用比較簡單,場景也比較清晰。protobuf中protobuf對應的java類就是使用建造者模式來建立物件的。
public static PersonEntity.Person create() { PersonEntity.Person person = PersonEntity.Person.newBuilder() .setId(1) .setName("Pushy") .setEmail("[email protected]") .build(); System.out.println(person); return person;}
一般建造者模式結合鏈式程式設計來使用,程式碼上更加美觀。
spring security`中也有使用到建造者模式,其 `AuthenticationManagerBuilder`是 `AuthenticationManager`的建造者,我們可以通過配置 `AuthenticationManagerBuilder`來建造一個 `AuthenticationManager public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); }}
我們來看看 AuthenticationManagerBuilder
public class AuthenticationManagerBuilder extends AbstractConfiguredSecurityBuilder<AuthenticationManager, AuthenticationManagerBuilder> implements ProviderManagerBuilder<AuthenticationManagerBuilder> { ...... ...... public final AuthenticationManager build() throws Exception { if (this.building.compareAndSet(false, true)) { this.object = this.doBuild(); return this.object; } else { throw new AlreadyBuiltException("This object has already been built"); } }}
這裡抽象建造者是 ProviderManagerBuilder
,具體建造者是 AuthenticationManagerBuilder
,被建造的物件是 AuthenticationManager
建造方法是 build()
方法。
一般建造者模式中建造者類命名以 builder
結尾,而建造方法命名為 build()
。
lombok中@builder就是對實體類使用創造者模式,如果你專案中用到了lombok那麼使用建造者模式就很方便,一個註解搞定。
點選關注我的部落格
點選關注我的博