我有两种来自上游的有效负载:它是PayloadA
或PayloadB
。
PayloadA
包含以下许多字段:
createTimestamp
sentTimestamp
schemaId
eventId
producerId
guid
deviceId
langId
sessionId
PayloadB
包含以下许多字段:
createTimestamp
sentTimestamp
schemaId
eventId
producerId
eventType
payloadVersion
creationDate
expirationSeconds
payload
所以前5个字段在它们之间很常见。一般来说,他们会有更多的领域。
我想为此创建一个线程安全构建器模式。那么我应该有一个Payload
构建器模式类,其中包含有效负载中的所有字段吗?或者我应该在另一个PayloadA
构建器类中包含PayloadB
和Payload
构建器模式类,并且PayloadA
和PayloadB
的公共字段将成为{{1}的一部分class?
为此类问题制作构建器模式的最佳方法是什么。假设Payload
构建器模式PayloadA
是必填字段。对于deviceId
构建器模式PayloadB
是必填字段。
答案 0 :(得分:1)
我建议在这里使用static nested builder (item 2)模式。
这是你可以做的事情
abstract
班级Payload
PayloadA
为PayloadB
创建Payload
和Builder
。Builder
不需要线程安全)。有效载荷
public abstract class Payload {
private String createTimestamp;
private String sentTimestamp;
private String schemaId;
private String eventId;
private String producerId;
//getters, setters, equals, hashcode, toString, compareTo, etc.
}
PayloadA(PayloadB类似)
class PayloadA extends Payload {
private String guid;
private String deviceId;
private String langId;
private String sessionId;
private PayloadA() {
//avoid direct instantiation
}
public static class Builder {
private String guid;
private String deviceId;
private String langId;
private String sessionId;
public Builder setLangId(String langId) {
this.langId = langId;
return this;
}
public Builder(String deviceId) {
//validations
this.deviceId = deviceId;
}
public PayloadA build() {
//validations
return new PayloadA();
}
//other setters returning this Builder
}
}
用法(从上游数据构建适当的有效负载
public Payload constructPayload(final Data data) {
//implement any thread safety mechanism as requirdhere.
// synchronized is just for explanatory purposes
synchronized (data) {
if (data.getType().equals("PayloadA")) {
return new PayloadA.Builder(data.getDeviceId())
//.setGuid("someGuid")
//other setters
.build();
} else {
return new PayloadB.Builder(data.getEventType())
//.setCreationDate("someCreationDate")
// other setters
.build();
}
}
}
希望这有帮助。