public class RabbitMQClient {
private RabbitMQClient(Builder builder){}
public void sendMessage(String msg){
System.out.println("发送消息 :" + msg);
}
public static class Builder{
private String host;
private int port;
private int mode;
private String exchange;
private String queue;
private boolean isDurable = true;
private int connectionTimeOut;
public Builder setHost(String host) {
this.host = host;
return this;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public Builder setMode(int mode) {
this.mode = mode;
return this;
}
public Builder setExchange(String exchange) {
this.exchange = exchange;
return this;
}
public Builder setQueue(String queue) {
this.queue = queue;
return this;
}
public Builder setDurable(boolean durable) {
isDurable = durable;
return this;
}
public Builder setConnectionTimeOut(int connectionTimeOut) {
this.connectionTimeOut = connectionTimeOut;
return this;
}
public RabbitMQClient build(){
//业务校验逻辑
return new RabbitMQClient(this);
}
}
}
public class App {
public static void main(String[] args) {
RabbitMQClient instance = new RabbitMQClient.Builder().setHost("127.0.0.1").setMode(2).setExchange("test").build();
instance.sendMessage("hello world");
}
}
建造者模式的好处:
1.构造函数不在需要传入一大堆参数了
2.解决了不可变对象的问题,例如上面的instance对象实际上只能调用提供业务的方法,对象被构建好后不再需要去动他了。