构造者模式 这里使用消息类来演示
MqMsgDto类
import com.tuan.pojo.ExchangeTypes;
import lombok.Builder;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author tuan
* @date 2021/01/21 11:21
**/
@Data
public class MqMsgDto {
private String uuId;
private String topic;
private String routingKey;
private String Exchange;
private String ExchangeType = "1";
private Map<String,Object> attarParameter = new HashMap<String,Object>();
public MqMsgDto() {
}
public MqMsgDto(String uuId, String topic, String routingKey, String exchange, String exchangeType, Map<String, Object> attarParameter) {
this.uuId = uuId;
this.topic = topic;
this.routingKey = routingKey;
Exchange = exchange;
ExchangeType = exchangeType;
this.attarParameter = attarParameter;
}
}
MqMsgDtoBuilder类
import com.tuan.pojo.ExchangeTypes;
import java.util.HashMap;
import java.util.Map;
/**
* Builder
* @author tuan
* @date 2021/01/21 11:37
**/
public class MqMsgDtoBuilder {
private String uuId;
private String topic;
private String routingKey;
private String exchange;
private String exchangeType = "1";
private Map<String,Object> attarParameter = new HashMap<String,Object>();
private MqMsgDtoBuilder(){
}
public static MqMsgDtoBuilder create(){
return new MqMsgDtoBuilder();
}
public MqMsgDtoBuilder withUuId(String uuId){
this.uuId = uuId;
return this;
}
public MqMsgDtoBuilder withTopic(String topic){
this.topic = topic;
return this;
}
public MqMsgDtoBuilder withRoutingKey(String routingKey){
this.routingKey = routingKey;
return this;
}
public MqMsgDtoBuilder withExchange(String exchange){
this.exchange = exchange;
return this;
}
public MqMsgDtoBuilder withExchangeType(String exchangeType){
this.exchangeType = exchangeType;
return this;
}
public MqMsgDtoBuilder withAttarParameters(Map<String,Object> parameters){
this.attarParameter = parameters;
return this;
}
public MqMsgDtoBuilder withAttarParameter(String key,Object value){
this.attarParameter.put(key,value);
return this;
}
public MqMsgDto build() throws Exception {
if (uuId == null){
throw new Exception("uuid is null");
}
if (topic == null){
throw new Exception("topic is null");
}
MqMsgDto mqMsgDto = new MqMsgDto(uuId, topic, routingKey, exchange, exchangeType, attarParameter);
return mqMsgDto;
}
}
测试Builder链路化
public static void main(String[] args) throws Exception {
MqMsgDto build = MqMsgDtoBuilder.create().withUuId("123")
.withExchange("123")
.withTopic(null)
.withRoutingKey("key")
.withAttarParameter("key", "object").build();
System.out.println("MqMsgDto "+build);
}