如何封装client/tool
单例
工具类,模板类,可以确定只用生成一个实例的,考虑这种设计模式,善用例模式。
在类中构造方法善用重载
Demo
public class ZooKeeperTemplate implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(ZooKeeperTemplate.class);
/** zookeeper session timeout: 30 seconds */
private static final int DEFAULT_SESSION_TIMEOUT_MILLISECONDS = 30_000;
/** zookeeper connect timeout: 60 seconds */
private static final int DEFAULT_CONNECT_TIMEOUT_MILLISECONDS = 60_000;
/** znode path separator */
private static final String PATH_SEPARATOR = "/";
public static ZooKeeperTemplate getInstance(String zooKeeperHost) {
return getInstance(zooKeeperHost, null, null);
}
public static ZooKeeperTemplate getInstance(String zooKeeperHost, Integer sessionTimeoutMilliseconds, Integer connectTimeoutMilliseconds) {
return new ZooKeeperTemplate(zooKeeperHost, sessionTimeoutMilliseconds, connectTimeoutMilliseconds);
}
private final String zooKeeperHost;
private final Integer sessionTimeoutMilliseconds;
private final Integer connectTimeoutMilliseconds;
private final ZooKeeper zoo;
private ZooKeeperTemplate(String zooKeeperHost, Integer sessionTimeoutMilliseconds, Integer connectTimeoutMilliseconds) {
this.zooKeeperHost = zooKeeperHost;
this.sessionTimeoutMilliseconds = defaultValue(sessionTimeoutMilliseconds, DEFAULT_SESSION_TIMEOUT_MILLISECONDS);
this.connectTimeoutMilliseconds = defaultValue(connectTimeoutMilliseconds, DEFAULT_CONNECT_TIMEOUT_MILLISECONDS);
this.zoo = connect();
}
//TODO 省略
} Builder构建器
这个设计模式也是数据创建型的,如果参与大于4个,推荐使用这种模式。
Demo
封装技巧
返回值
使用Optinal包装返回值,避免返回值为null
统一校验
在类中的多个方法都需要相同的参数校验的,抽象出统一校验,jdk源码中就存在大量这样的例子。
下面举个例子:
AutoCloseable/Closeable
需要关闭资源的,记得实现AutoCloseable/Closeable
最后更新于
这有帮助吗?