抽象建造者定义建造的零件方法和获取产品的方法,具体建造者实现这些方法。
导演角色主要调用具体建造者角色用以创建产品对象
产品角色是建造的最终产品,一般来说一个系统会有多于一个的产品类,而且这些产品类并不一定有共同的接口,可以完全是不相关联的。
下面依然以造车示例建造者模式:
public class BuilderDemo { static class Director { private Builder builder; public Car constructAccord() { builder = new AccordBuilder(); builder.buildChassis(); builder.buildEngine(); builder.buildWheel(); builder.buildTransmission(); return builder.getProduct(); } } static class Car { private String chassis; private String wheel; private String Engine; private String Transmission; public String toString() { StringBuilder sb = new StringBuilder(); sb.append("发动机:" + this.getEngine()+" "); sb.append("轮胎:" + this.getWheel()+" "); sb.append("变速箱:" + this.getTransmission()+" "); sb.append("底盘:" + this.getChassis()+" "); return sb.toString(); } public String getChassis() { return chassis; } public void setChassis(String chassis) { this.chassis = chassis; } public String getWheel() { return wheel; } public void setWheel(String wheel) { this.wheel = wheel; } public String getEngine() { return Engine; } public void setEngine(String engine) { Engine = engine; } public String getTransmission() { return Transmission; } public void setTransmission(String transmission) { Transmission = transmission; } } interface Builder { void buildChassis(); void buildWheel(); void buildEngine(); void buildTransmission(); Car getProduct(); } static class AccordBuilder implements Builder { Car car = new Car(); @Override public void buildChassis() { this.car.setChassis("好底盘"); } @Override public void buildWheel() { this.car.setWheel("倍耐力轮胎"); } @Override public void buildEngine() { this.car.setEngine("地球梦发动机"); } @Override public void buildTransmission() { this.car.setTransmission("10AT变速箱"); } @Override public Car getProduct() { return this.car; } } public static void main(String[] args) { Director director = new Director(); Car accord = director.constructAccord(); System.out.println("---生产出一辆雅阁---"); System.out.println(accord.toString()); } }
建造者模式的导演者其实可以去除,如果只有一种构建的产品,那么其实也就不需要导演者这个角色了。
去掉导演者角色的建造者设计模式其实就是“模板方法设计模式”