一、UML类图
二、代码示例
public class Client {
public static void main(String[] args) {
Builder builder = new ConcreteBuilder();
Director director = new Director(builder);
director.construct();
Product product = builder.getProduct();
}
}
public interface Builder {
void buildPart1();
void buildPart2();
Product getProduct();
}
public class ConcreteBuilder implements Builder{
private Product product = new Product();
@Override
public void buildPart1() {
product.setPart1("part1");
}
@Override
public void buildPart2() {
product.setPart2("part2");
}
@Override
public Product getProduct() {
return product;
}
}
public class Director {
private Builder builder = null;
public Director(Builder builder) {
this.builder = builder;
}
public void construct() {
this.builder.buildPart1();
this.builder.buildPart2();
}
}
public class Product {
private String part1;
private String part2;
public String getPart1() {
return part1;
}
public void setPart1(String part1) {
this.part1 = part1;
}
public String getPart2() {
return part2;
}
public void setPart2(String part2) {
this.part2 = part2;
}
}
三、角色介绍
- Client(客户端):
客户端角色,程序的调用者。 - Builder(建造者):
负责定义用于生成实例的接口。 - ConcreteBuilder(具体的建造者):
负责定义生成实例时实际被调用的方法,并获取最终生成的结果。 - Director(监工):
负责使用Builder角色的接口来生成实例。 - Product(产品):
所生成的具体实例。
|