public class GsonUtils {
private static class Holder {
static final Gson INSTANCE = new Gson();
}
public static Gson getInstance() {
return Holder.INSTANCE;
}
}
it s all;
public class GsonUtils {
private static class Holder {
static final Gson INSTANCE = new Gson();
}
public static Gson getInstance() {
return Holder.INSTANCE;
}
}
it s all;
As mentioned in the comments, you can pull the field INSTANCE
up to class level. No need for another encapsulation that does nothing.
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;
}
}
You can also lazy initialize the singleton:
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;
}
}
See Java Singleton Pattern for a more detailed explanation.