百度百科
https://baike.baidu.com/item/%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F/3229729
基本介绍
四个角色
原理类图
本文事例UML图
product:
// 产品
public class House {
private String baise;
private String wall;
private String roofed;
public String getBaise() {
return baise;
}
public void setBaise(String baise) {
this.baise = baise;
}
public String getWall() {
return wall;
}
public void setWall(String wall) {
this.wall = wall;
}
public String getRoofed() {
return roofed;
}
public void setRoofed(String roofed) {
this.roofed = roofed;
}
}
抽象创造者
// 抽象的建造者
public abstract class HouseBuilder {
protected House house = new House(); // 组合产品房子
// 将建造的流程写好,抽象的方法
public abstract void buildBasic();
public abstract void buildWalls();
public abstract void roofed();
public House buildHouse() {
return house;
}
}
指挥者:
//指挥者,制作流程,返回产品
public class HouseDirector {
HouseBuilder houseBuilder = null;
public HouseDirector(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
public HouseBuilder getHouseBuilder() {
return houseBuilder;
}
public void setHouseBuilder(HouseBuilder houseBuilder) {
this.houseBuilder = houseBuilder;
}
//处理建造房子的流程,业务逻辑 ,交给指挥者
public House constructHouse() {
houseBuilder.buildBasic();
houseBuilder.buildWalls();
houseBuilder.roofed();
return houseBuilder.buildHouse();
}
}
具体创建者,比如高楼和矮楼:
package builder;
public class CommonHouse extends HouseBuilder {
@Override
public void buildBasic() {
System.out.println("普通房子打地基6米");
}
@Override
public void buildWalls() {
System.out.println("普通房子砌墙10米");
}
@Override
public void roofed() {
System.out.println("普通房子正常封顶");
}
}
package builder;
public class HighBuilding extends HouseBuilder {
@Override
public void buildBasic() {
System.out.println("高楼大厦打地基50米");
}
@Override
public void buildWalls() {
System.out.println("高楼大厦砌墙100米");
}
@Override
public void roofed() {
System.out.println("高楼大厦透明封顶");
}
}
测试结果:
JDK源码:
创建者模式的注意事项和细节