builder 模式是为了隐藏对象的创建过程,并且很好地管理大量的创建对象参数。在《effective java》中就强烈推荐了这种创建对象的模式。
在NameNode中构建RPCServer会使用到这段代码:
this.serviceRpcServer = new RPC.Builder(conf)
.setProtocol( org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolPB.class)
.setInstance(clientNNPbService)
.setBindAddress(bindHost) .setPort(serviceRpcAddr.getPort()).setNumHandlers(serviceHandlerCount).setVerbose(false) .setSecretManager(namesystem.getDelegationTokenSecretManager())
.build();
如何管理大量的对象创建参数:在这段代码中可以清楚地知道每一个参数的意义,因为每一个参数都在一个方法里面。.setBindAddress(bindHost) 这样就可以知道binHost参数是一个BindAddress。代码重构的时候也推荐抽出方法,来体现一段代码的意义。每一个方法的方法名是非常重要的。
来看一下Buider方法的主体部分:
public static class Builder {
private Class<?> protocol = null;
private Object instance = null;
private String bindAddress = "0.0.0.0";
private int port = 0;
private int numHandlers = 1;
private int numReaders = -1;
private int queueSizePerHandler = -1;
private boolean verbose = false;
private final Configuration conf;
private SecretManager<? extends TokenIdentifier> secretManager = null;
private String portRangeConfig = null;
public Builder(Configuration conf) {
this.conf = conf;
}
//此处省略大段代码
/**
* Build the RPC Server.
* @throws IOException on error
* @throws HadoopIllegalArgumentException when mandatory fields are not set
*/
public Server build() throws IOException, HadoopIllegalArgumentException {
if (this.conf == null) {
throw new HadoopIllegalArgumentException("conf is not set");
}
if (this.protocol == null) {
throw new HadoopIllegalArgumentException("protocol is not set");
}
if (this.instance == null) {
throw new HadoopIllegalArgumentException("instance is not set");
}
return getProtocolEngine(this.protocol, this.conf).getServer(this.protocol, this.instance, this.bindAddress,this.port,this.numHandlers,this.numReaders,this.queueSizePerHandler,this.verbose, this.conf, this.secretManager, this.portRangeConfig);
}
}
截取两段比较重要的地方,第一段是这个builder模式是可以有默认值的。private String bindAddress = “0.0.0.0”;这一段将bindAddress的默认值设置为了0.0.0.0。
第二段是builder 方法。它返回了一个Server。并且将Server的创建封装在方法内部。