介绍
Java的建造者(Builder)设计模式可以将产品的内部表现和产品的构建过程分离开来,这样使用同一个构建过程来构建不同内部表现的产品。
建造者设计模式涉及如下角色:
- 产品(Product)角色:被建造的复杂对象。对象包括了多个部分,这些部分有可能有顺序关系,需要按照一定的顺序来创建。
- 抽象构建者(Builder)角色:定义了构建产品各部分的接口,一般产品中的每个部分对应一个接口。另外,还提供返回产品的接口。抽象构建者跟具体的业务逻辑无关。
- 具体构建者(Concrete Builder)角色:实现抽象构建者的接口,跟具体的业务逻辑相关,完成具体产品各部分的构建。如果要构建的不同产品包含的部件数量不完全相同,那也可以在抽象构建者角色中定义一套全的接口,但在具体构建者角色中对产品没有的那部分部件的构建接口实现为空。
- 导演者(Diretor)角色:直接和客户端打交道,调用具体构建者角色创建具体的产品。
代码示例
定义一个产品:
package com.thb;
public class Packet {
private String header;
private String content;
private int contentLength;
public void setHeader(String header) {
this.header = header;
}
public void setContent(String content) {
this.content = content;
}
public void setContentLength() {
this.contentLength = content.length();
}
public void showSummary() {
System.out.println("header: " + this.header);
System.out.println("content: " + this.content);
System.out.println("contentLength: " + this.contentLength);
}
}
定义抽象构建者:
package com.thb;
public abstract class Builder {
protected Packet packet;
public Builder() {
this.packet = new Packet();
}
public abstract void builidHeader();
public abstract void builidContent();
public void builidContentLength() {
this.packet.setContentLength();
}
public Packet getResult() {
return this.packet;
}
}
定义一个具体构建者:
package com.thb;
public class HeartBeatPacketBuilder extends Builder {
@Override
public void builidHeader() {
this.packet.setHeader("heartbeat header");
}
@Override
public void builidContent() {
this.packet.setContent("heartbeat content");
}
}
定义另外一个具体构建者:
package com.thb;
public class RegisterPacketBuilder extends Builder {
@Override
public void builidHeader() {
this.packet.setHeader("register header");
}
@Override
public void builidContent() {
this.packet.setContent("register content");
}
}
定义导演者:
package com.thb;
public class Director {
private Builder builder;
public Packet construct(Builder builder) {
this.builder = builder;
builder.builidHeader();
builder.builidContent();
builder.builidContentLength();
return this.builder.getResult();
}
}
定义主类,模拟客户端调用:
package com.thb;
public class Test1 {
public static void main(String[] args) {
Director director = new Director();
Builder heartBeatPacketBuilder = new HeartBeatPacketBuilder();
Packet heartBeatPacket = director.construct(heartBeatPacketBuilder);
heartBeatPacket.showSummary();
System.out.println("------------------------------------");
Builder registerPacketBuilder = new RegisterPacketBuilder();
Packet registerPacket = director.construct(registerPacketBuilder);
registerPacket.showSummary();
}
}
运行输出: