本模式能夠看出與抽象工廠很是相似,都是產生不一樣的產品,怎麼區分這兩種設計的使用場景呢 - 建造者模式關注的是基本方法的調用順序,而零件(基本方法)已經準備好 - 抽象工廠關注的零件的生產(基本方法的實現),而組裝順序已經肯定
產品抽象ide
public abstract class Product { public abstract void doSomeThing(); }
產品Aui
public class AProduct extends Product { @Override public void doSomeThing() { } }
產品B設計
public class BProduct extends Product { @Override public void doSomeThing() { } }
抽象建造者code
public abstract class AbstractBuilder { private List<String> methodList = new ArrayList(); /** * 建造方法(模板方法) * 按照定製的執行順序執行方法 * * @return */ protected abstract Product build(); /** * 基本方法 */ protected void methodA(){ } /** * 基本方法 */ protected void methodB(){ } /** * 基本方法 */ protected void methodC(){ } /** * 設置建造的內部邏輯(配置零件) */ public abstract void setPart(); }
建造者實現blog
public class ABuilder extends AbstractBuilder { private List<String> aList = new ArrayList(); private List<String> bList = new ArrayList(); private List<String> cList = new ArrayList(); private Product product = new AProduct(); @Override protected Product build() { if(CollectionUtils.isEmpty(aList)){ methodA(); } if(CollectionUtils.isEmpty(bList)){ methodA(); } methodC(); // 一些業務邏輯處理 return product; } @Override public void setPart() { //避免引發邏輯錯誤 aList.clear(); bList.clear(); cList.clear(); aList.add("A1"); aList.add("A2"); aList.add("A3"); bList.add("B2"); } }
建造者實現get
public class BBuilder extends AbstractBuilder { private List<String> aList = new ArrayList(); private List<String> bList = new ArrayList(); private List<String> cList = new ArrayList(); private Product product = new BProduct(); @Override protected Product build() { if(CollectionUtils.isEmpty(aList)){ methodA(); } methodC(); if(CollectionUtils.isEmpty(bList)){ methodB(); } // 一些業務邏輯處理 return product; } @Override public void setPart() { //避免引發邏輯錯誤 aList.clear(); bList.clear(); cList.clear(); bList.add("A1"); bList.add("A2"); bList.add("A3"); cList.add("B2"); } }
導演類,封裝實現,避免高層深刻具體的建造者接觸(能夠有多個)產品
public class Director { private ABuilder aBuilder = new ABuilder(); private BBuilder bBuilder = new BBuilder(); public Product getAProduct(){ return aBuilder.build(); } public Product getBProduct(){ return bBuilder.build(); } }
調用io
public class Client { public static void main(String[] args) { Director director = new Director(); Product aProduct = director.getAProduct(); aProduct.doSomeThing(); } }