构建模式的核心就是把构建和表示进行分离、解耦,如下例子:Part类代表一个复杂的需要构建的实体,其中有两个属性,代表需要的组件,Builder接口,用于表示需要构建的步骤方法,也可以理解为构建部分,Yw,Zw类表示不同的表示方式,也就是Part类在不同的情况下表现出来的不同view,Director类选择不同的Builder实现会得到不同的result给client,其中最核心的是Builder接口和Director类,通过这两个部件我们可以用不同的部件任意组合不同的Part给调用者。
package com.jerry.design.builder; public class Part { private String name; private String code; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
package com.jerry.design.builder; public interface Builder { public void builderPartA(Part p); public void builderPartB(Part p); public String getResult(); }
package com.jerry.design.builder; public class Director { private Builder bulider; public void setBulider(Builder bulider) { this.bulider = bulider; } public String doSomething(Part p){ bulider.builderPartA(p); bulider.builderPartB(p); return bulider.getResult(); } }
package com.jerry.design.builder; public class Yw implements Builder{ private StringBuffer result = new StringBuffer("english:"); @Override public void builderPartA(Part p) { result.append(p.getName()); } @Override public void builderPartB(Part p) { result.append(p.getCode()); } @Override public String getResult() { return result.toString(); } }
package com.jerry.design.builder; public class Zw implements Builder{ private StringBuffer result = new StringBuffer("中文:"); @Override public void builderPartA(Part p) { result.append(p.getName()); } @Override public void builderPartB(Part p) { result.append(p.getCode()); } @Override public String getResult() { return result.toString(); } }
package com.jerry.design.builder; public class Client { public static void main(String[] args) { Part p = new Part(); p.setName("我的名字"); p.setCode("我的代码"); Zw zw = new Zw(); Director dir = new Director(); dir.setBulider(zw); System.out.println(dir.doSomething(p)); } }