一、定义

将一个复杂对象的构建与它的表现分离,以便用同样的构建过程创建不同的表现。

二、类图表示

建造者模式

三、实现

1、Product

package pattern.creational.builder;

import java.util.Hashtable;

import pattern.creational.Constants;

public class Vehicle {

	private String type;
	private Hashtable<String, String> parts = new Hashtable<>();
	
	public Vehicle(String type) {
		this.type = type;
	}
	public String getType() {
		return type;
	}
	public String get(String key){
		return parts.get(key);
	}
	public void set(String key, String value){
		parts.put(key, value);
	}
	@Override
	public String toString() {
		Object[] args = new String[]{this.getType(), get(Constants.ENGINE), get(Constants.WHEELS), get(Constants.DOORS)};
		return String.format(" Vehicle Type: %s\n Engine: %s\n Wheels: %s\n Doors: %s", args);
	}
}

2、Builder

  • Builder
package pattern.creational.builder;

public abstract class VehicleBuilder {

	protected Vehicle vehicle;
	
	public abstract void buildEngine();
	public abstract void buildWheels();
	public abstract void buildDoors();
	
	public Vehicle getResult(){
		return vehicle;
	}
}

  • ConcreteBuilder
package pattern.creational.builder;

import pattern.creational.Constants;

public class CarBuilder extends VehicleBuilder {

	public CarBuilder() {
		this.vehicle = new Vehicle("car");
	}
	
	@Override
	public void buildEngine() {
		vehicle.set(Constants.ENGINE, "V8");
	}

	@Override
	public void buildWheels() {
		vehicle.set(Constants.WHEELS, "4");
	}

	@Override
	public void buildDoors() {
		vehicle.set(Constants.DOORS, "4");
	}

}


package pattern.creational.builder;

import pattern.creational.Constants;

public class BikeBuilder extends VehicleBuilder {

	public BikeBuilder() {
		this.vehicle = new Vehicle("bike");
	}
	
	@Override
	public void buildEngine() {
		vehicle.set(Constants.ENGINE, "none");
	}

	@Override
	public void buildWheels() {
		vehicle.set(Constants.WHEELS, "2");
	}

	@Override
	public void buildDoors() {
		vehicle.set(Constants.DOORS, "0");
	}

}

3、Director

package pattern.creational.builder;

public class Director {

	public void construct(VehicleBuilder builder){
		builder.buildEngine();
		builder.buildWheels();
		builder.buildDoors();
	}
}

四、使用

package pattern.creational.builder;

public class Client {

	public static void main(String[] args) {
		Director director = new Director();
		VehicleBuilder carBuilder = new CarBuilder();
		VehicleBuilder bikeBuilder = new BikeBuilder();
		director.construct(carBuilder);
		director.construct(bikeBuilder);
		System.out.println(carBuilder.getResult());
		System.out.println("--------------------");
		System.out.println(bikeBuilder.getResult());
	}
}

  • 程序输出

五、适用场合

  • 当创建的对象内部结构比较复杂时
  • 当对象的创建需要和它的表现分离时