先看一张自动生成的序列图
说明:建造房子是我们的目标house,建造房子要有工人worker,工人工作要有工序builder,有了工序就是付出实际的劳动ConcreteBuilder
再看实现的代码
package com.example.demohystrix.designpattern.creation.build; /** * @author liusongwei * @Title: House * @ProjectName demohystrix * @Description: 房子 * @date 2018/12/249:55 */ public class House { private String basic; private String wall; private String roof; public String getBasic() { System.out.println(basic); return basic; } public void setBasic(String basic) { this.basic = basic; } public String getWall() { System.out.println(wall); return wall; } public void setWall(String wall) { this.wall = wall; } public String getRoof() { System.out.println(roof); return roof; } public void setRoof(String roof) { this.roof = roof; } }
package com.example.demohystrix.designpattern.creation.build; /** * @author liusongwei * @Title: Builder * @ProjectName demohystrix * @Description: 抽象建造者 * @date 2018/12/2410:06 */ public interface Builder { public void buildbasic(); public void buildwall(); public void buildroof(); public House buildHose(); }
package com.example.demohystrix.designpattern.creation.build; /** * @author liusongwei * @Title: ConcreteBuilder * @ProjectName demohystrix * @Description: 建造的过程包括 * @date 2018/12/2410:54 */ public class ConcreteBuilder implements Builder { private House house; public ConcreteBuilder(){ house = new House(); } @Override public void buildbasic() { house.setBasic("打地基"); } @Override public void buildwall() { house.setWall("工人砌墙"); } @Override public void buildroof() { house.setRoof("给房子封顶"); } @Override public House buildHose() { return house; } }
package com.example.demohystrix.designpattern.creation.build; /** * @author liusongwei * @Title: Worker * @ProjectName demohystrix * @Description: 工人造房子 * @date 2018/12/2410:59 */ public class Worker { public House buildHouse(ConcreteBuilder concreteBuilder){ concreteBuilder.buildbasic(); concreteBuilder.buildwall(); concreteBuilder.buildroof(); return concreteBuilder.buildHose(); } }
package com.example.demohystrix.designpattern.creation.build; /** * @author liusongwei * @Title: Demo * @ProjectName demohystrix * @Description: TODO * @date 2018/12/2411:02 */ public class Demo { public static void main(String[] args){ Worker worker = new Worker(); House house = worker.buildHouse(new ConcreteBuilder()); house.getBasic(); house.getWall(); house.getRoof(); } }
建造者模式的定义是:将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示,这样的设计模式被称为建造者模式。
本质:
--分离对象子组件的单独构造(由Buider来负责)和装配(由Director负责)。从而可以构造出复杂的对象。这个模式适用于:某个对象的构建过程复杂的情况下使用。
--由于实现构造和装配的解耦。不同的构造器,相同的装配,也可以做出不同的对象;相同的构造器,不同的装配顺序也可以做出不同的对象。也就是实现了构建算法、装配算法的解耦,实现了更好的复用。