我有一个单例课程,它的功能非常好。我现在想知道最后一种方法是做什么用的?
public class PicassoSingleton {
private static Picasso instance;
public static Picasso with(Context context) {
if (instance == null) {
instance = new Picasso.Builder(context.getApplicationContext()).debugging(true).downloader(new ImageDownloader(context)).build();
}
return instance;
}
private PicassoSingleton() {
throw new AssertionError("No instances.");
}
}
有谁知道它的作用或用途是什么?
通常,使构造函数private
阻止其他类实例化a就足够了PicassoSingleton
。
在私有构造函数中抛出异常似乎是偏执的编程,因为类的实现者知道它的内部细节,并且必须知道他的工作。
但这是有道理的。在构造函数中抛出异常还将阻止其他人使用反射实例化该类的对象。
这是不可能的
Constructor<PicassoSingleton> constructor = PicassoSingleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance(); // will throw the AssertionError - impossible to instantiate it
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句