角色:
1. builder抽象建造者: 为创建一个产品对象的各个部件指定抽象接口.
2. ConcreteBuilder具体建造者: 实现Builder的接口以构造和装配该产品的各个部件,定义并明确它所创建的表示,并提供一个检索产品的接口.
3. Director导演:负责安排已有模块的顺序,然后告诉Builder开始建造.
4. Product产品类: 表示被构造的复杂对象.通常实现了模板方法模式.
类图:
实例:
//Builder
public interface PersonBuilder {
void buildHead();
void buildBody();
void buildFoot();
Person buildPerson();
}
//ConcreteBuilder
public class ManBuilder implements PersonBuilder {
Person person;
public ManBuilder() {
person = new Man();
}
public void buildbody() {
person.setBody("建造男人的身体");
}
public void buildFoot() {
person.setFoot("建造男人的脚");
}
public void buildHead() {
person.setHead("建造男人的头");
}
public Person buildPerson() {
return person;
}
}
//Dirictor
public class PersonDirector {
public Person constructPerson(PersonBuilder pb) {
pb.buildHead();
pb.buildBody();
pb.buildFoot();
return pb.buildPerson();
}
}
//Product
public class Person {
private String head;
private String body;
private String foot;
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getFoot() {
return foot;
}
public void setFoot(String foot) {
this.foot = foot;
}
}
public class Man extends Person {
}
//Test
public class Test{
public static void main(String[] args) {
PersonDirector pd = new PersonDirector();
Person person = pd.constructPerson(new ManBuilder());
System.out.println(person.getBody());
System.out.println(person.getFoot());
System.out.println(person.getHead());
}
}