1.定义:
- 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
- UML图
2.示例:
汽车或者电脑的组装可以采用构造者模式进行设计,如汽车的引擎或者轮胎,电脑的处理器、内存、主板等都可以进行单独的设计和组装。下面已汽车组装为例:
- 首先是汽车对象:
public class Car {/*** 引擎*/private String engine;/*** 轮胎*/private String tire;/*** 外壳*/private String shell;/*** 品牌*/private String brand;public String getEngine() {return engine;}public void setEngine(String engine) {this.engine = engine;}public String getTire() {return tire;}public void setTire(String tire) {this.tire = tire;}public String getShell() {return shell;}public void setShell(String shell) {this.shell = shell;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}@Overridepublic String toString() {return "Car{" +"engine='" + engine + '\'' +", tire='" + tire + '\'' +", shell='" + shell + '\'' +", brand='" + brand + '\'' +'}';}
}
- 车辆构建抽象层 也就是builder,规范车辆的构造
public interface VehicleBuilder {/*** 引擎*/void engine();/*** 轮胎*/void tire();/*** 外壳*/void shell();/*** 品牌*/void brand();/*** 创建汽车** @return*/Car createCar();}
- 车辆构建指挥者 director,主要负责最终的组装
public class VehicleDirector {public Car createVehicle(VehicleBuilder vehicleBuilder) {vehicleBuilder.engine();vehicleBuilder.tire();vehicleBuilder.brand();vehicleBuilder.shell();return vehicleBuilder.createCar();}
}
- 具体的车辆构造器,采用什么材料或者部件构造一辆车,实现或者继承抽象构造层可以关联具体的产品
public class BMWVehicleBuilder implements VehicleBuilder {private Car car = new Car();@Overridepublic void engine() {car.setEngine("V8引擎");}@Overridepublic void tire() {car.setTire("米其林轮胎");}@Overridepublic void shell() {car.setShell("钛合金外壳");}@Overridepublic void brand() {car.setBrand("宝马X5");}@Overridepublic Car createCar() {return this.car;}
}
- 测试
public class Main {public static void main(String[] args) {VehicleDirector vehicleDirector = new VehicleDirector();VehicleBuilder bmwVehicleBuilder = new BMWVehicleBuilder();Car vehicle = vehicleDirector.createVehicle(bmwVehicleBuilder);System.out.println(vehicle);}
}
总结
- 优点:
- 隐藏具体的建造细节,将产品本身与产品的创建过程解耦
- 具体建造者之间相对独立,可以更加精细地控制产品的创建过程
- 新增具体建造者无须修改原有类库的代码,符合开闭原则
- 缺点:
- 创建的产品的需要有较多的共同点,否则使用效果不理想
- 也会增加系统代码的复杂度,使其更为抽象,维护难度增大