最近准备写点Javase的东西,希望可以帮助大家写出更好的代码。
1、给不可实例化的类提供私有构造器
比如:每个项目中都有很多工具类,提供了很多static类型的方法供大家使用,谁也不希望看到下面的代码:
TextUtils textUtils = new TextUtils();
if(textUtils.isDigitsOnly("123"))
{
//doSometing
}else
{
//doSomething
}自己写个工具类,总有人喜欢先初始化个实例在调用方法,然后还附带一个警告:The static method isDigitsOnly(CharSequence) from the type TextUtils should be accessed in a static way 。 你建议他使用类名.方法,人家还不乐意,我又没出错,干嘛要改,错了你负责么。所以最好的方式,让他没办法new实例。
为工具类添加私有构造器:
public class TextUtils {
private TextUtils() { /* cannot be instantiated */ }
这是android的TextUtils的源码,这样就可以了,让他妹的初始化实例~,当然你也可以在私有方法里面扔个异常。
public class TextUtils
{
private TextUtils()
{
/* cannot be