概念:
即采用构建者和构建工具两个角色来封装复杂对象及其子对象的创建过程(子对象一般都具有多边性)。
要点:
1、 创建构建工具(接口+实现类),封装对象和子对象创建过程
2、创建构建者,封装创建工具的创建细节,供消费者使用
实例:
1、pojo类
/**
* 汽车实体类
* 简单起见,每个汽车封装了两个复杂对象引擎和轮子
* 引擎和轮子都具有复杂性和多变性两个特点
*
* @author ypqiao
*
*/
public class Car {
private String engine;
private String wheel;
protected Car( String engine, String wheel ){
this.engine = engine;
this.wheel = wheel;
}
protected Car(){
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getWheel() {
return wheel;
}
public void setWheel(String wheel) {
this.wheel = wheel;
}
}
2、构建者工具接口
/**
* 汽车构建工具统一接口
*
* 封装汽车及其子部件构建细节
*
* @author ypqiao
*
*/
public interface Builder {
/**
* 构建引擎
* @throws Exception
*/
public void buildEngine() throws Exception;
/**
* 构建轮子
* @throws Exception
*/
public void buildWheel() throws Exception;
/**
* 构建汽车
* @return
* @throws Exception
*/
public Car getCar() throws Exception;
}
2.1、宝马构建工具实现
/**
* 宝马汽车构建工具
*
* @author ypqiao
*
*/
public class BaomaBuilder implements Builder {
private String engine;
private String wheel;
@Override
public void buildEngine() throws Exception {
engine = "BaoMa-engine";
}
@Override
public void buildWheel() throws Exception {
wheel = "BaoMa-wheel";
}
@Override
public Car getCar() throws Exception {
return new Car(engine,wheel);
}
}
2.2、奔驰构建工具实现
/**
* 奔驰汽车构建工具
*
* @author ypqiao
*
*/
public class BenchBuilder implements Builder {
private String engine;
private String wheel;
@Override
public void buildEngine() throws Exception {
engine = "Bench-engine";
}
@Override
public void buildWheel() throws Exception {
wheel = "Bench-wheel";
}
@Override
public Car getCar() throws Exception {
return new Car(engine,wheel);
}
}
3、构建者类
/**
* 构建者
*
* 封装构建工具构建细节
*
* @author ypqiao
*
*/
public class Director {
public Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void constrct() throws Exception{
if( builder == null ){
throw new RuntimeException(" no builder ");
}
builder.buildEngine();
builder.buildWheel();
}
}
4、消费者(此时它想创建一辆汽车,只需调用构建工具盒构建者即可,不必知道汽车具体的创建细节)
/**
* 汽车产品消费类
*
* @author ypqiao
*
*/
public class Customer {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//Builder baomaBuilder = new BaomaBuilder();
Builder benchBuilder = new BenchBuilder();
Director director = new Director(benchBuilder);
director.constrct();
Car car = benchBuilder.getCar();
System.out.println(car.getEngine()+"\n"+car.getWheel());
}
}