public class GsonUtils {
private static class Holder {
static final Gson INSTANCE = new Gson();
}
public static Gson getInstance() {
return Holder.INSTANCE;
}
}
全部;
答案 0 :(得分:0)
如评论中所述,您可以将字段INSTANCE
提升到班级。不需要其他无效的封装。
public class GsonUtils {
private static final Gson INSTANCE = new Gson();
private GsonUtils() {
// you do not want someone to instantiate this
}
public static Gson getInstance() {
return INSTANCE;
}
}
你也可以懒惰地初始化单身:
public class GsonUtils {
private static Gson INSTANCE;
private GsonUtils() {
// you do not want someone to instantiate this
}
public static Gson getInstance() {
if(INSTANCE == null) {
INSTANCE = new Gson();
}
return INSTANCE;
}
}
有关更详细的说明,请参阅Java Singleton Pattern。