工具类中屏蔽构造函数

工具类中屏蔽构造函数

参考网址:

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为每个类添加了一个隐式公共构造函数,而这些类至少没有显式定义一个。因此,应至少定义一个非公共构造函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值