先上个简陋的类图,后面把rose专业的画类图软件装上,自己为了学习留个笔记,方便以后查找使用,以下的例子从构建一个Person展开。
Coding:
1、构建者接口设计
public interface IBuilder {
public void buildHead();
public void buildBody();
public void buildFoot();
public Person buildPerson();
}
2、Person实体类
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;
}
}
3、构建一个普通人
public class HumanBuilder implements IBuilder {
private Person person;
public HumanBuilder() {
this.person = new Person();
}
@Override
public void buildBody() {
this.person.setBody("普通人的身体*****************");
}
@Override
public void buildFoot() {
this.person.setFoot("普通人的脚*****************");
}
@Override
public void buildHead() {
this.person.setHead("普通人的头*****************");
}
@Override
public Person buildPerson() {
return this.person;
}
}
4、构建一个变形金刚
public class TransformerBuilder implements IBuilder {
private Person person;
public TransformerBuilder() {
this.person = new Person();
}
@Override
public void buildBody() {
this.person.setBody("变形金刚的身体*****************");
}
@Override
public void buildFoot() {
this.person.setFoot("变形金刚的脚*****************");
}
@Override
public void buildHead() {
this.person.setHead("变形金刚的头*****************");
}
@Override
public Person buildPerson() {
return this.person;
}
}
5、建造者构建导向
//构建人的构建导向
public class PersonDirector {
public Person constructorPerson(IBuilder builder) {
builder.buildHead();
builder.buildBody();
builder.buildFoot();
return builder.buildPerson();
}
}
6、客户端调用
public class Client {
public static void main(String[] args) {
PersonDirector pd = new PersonDirector();
// Person p = pd.constructorPerson(new HumanBuilder());
Person p = pd.constructorPerson(new TransformerBuilder());
System.out.println(p.getHead());
System.out.println(p.getBody());
System.out.println(p.getFoot());
}
}
7、构建者模式和工厂模式有其相通的地方,有兴趣的朋友可以对照着工厂模式和构建者模式做一个比较,构建者模式在某些应用场景下是非常适合和构建者模式结合使用的。