工具类中屏蔽构造函数
参考网址:
https://mp.weixin.qq.com/s/LG92rkjY3o2pqx3QdaXBVw
错误示例代码
public class PasswordUtils {
//工具类构造函数反例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
正确示例代码
public class PasswordUtils {
//工具类构造函数正例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
//定义私有构造函数来屏蔽这个隐式公有构造函数
private PasswordUtils(){}
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
代码审查解释
Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
实用程序类是静态成员的集合,不需要实例化。即使是可以扩展的抽象实用程序类也不应该有公共构造函数。
Java为每个类添加了一个隐式公共构造函数,而这些类至少没有显式定义一个。因此,应至少定义一个非公共构造函数。