1. 类图
- Builder:创造者接口,定义创建一个Product对象所需要的各个部件的操作
- ConcreteBuilder:具体的创造者实现,创建各个部件并进行组装,同时还提供一个让用户获取组装完成后的产品对象的方法
- Director:指挥者,主要用来使用Builder接口,以一个统一的过程来构建所需要的Product对象
- Product:具体产品,包含多个部件
2. 示例
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
2.1 创建者接口
public abstract class AbstractBuilder {
Meal meal = new Meal();
public abstract void buildFood();
public abstract void buildDrink();
public Meal getMeal(){return meal;}
}
2.2 接口实现
public class SetMealA extends AbstractBuilder {
public void buildFood() {meal.setFood("油条");}
public void buildDrink() {meal.setDrink("豆浆");}
}
public class SetMealB extends AbstractBuilder {
public void buildFood() {meal.setFood("面包");}
public void buildDrink() {meal.setDrink("牛奶");}
}
2.3 具体产品
public class Meal {
private String food;
private String drink;
public void setFood(String food) {
this.food = food;
}
public void setDrink(String drink) {
this.drink = drink;
}
@Override
public String toString() {
return "Meal{" +
"food='" + food + '\'' +
", drink='" + drink + '\'' +
'}';
}
}
2.4 指挥者
public class Director {
private AbstractBuilder builder;
public Director(AbstractBuilder builder) {this.builder = builder;}
public Meal provideMeal() {
builder.buildFood();
builder.buildDrink();
return builder.getMeal();
}
}
2.4 客户端
public class Client {
public static void main(String[] args) {
System.out.println(new Director(new SetMealA()).provideMeal());
}
}
3. 优点
- 将整体的构建算法和部件构造分离,松散耦合
- 可以很容易改变产品内部的表示
- 更好的复用性