-3
public class GsonUtils {

    private static class Holder {
        static final Gson INSTANCE = new Gson();
    }

    public static Gson getInstance() {
        return Holder.INSTANCE;
    }
}

it s all;

Coder
  • 1,917
  • 3
  • 17
  • 33
Mc Mike
  • 3
  • 1
  • 6
  • 1
    as there is no class `Gson` shown, probably not as you initialize it from another class. – SomeJavaGuy Dec 21 '16 at 06:36
  • 1
    The `Holder` class is useless here. Just bring the field into `GsonUtils`. – Sotirios Delimanolis Dec 21 '16 at 06:38
  • public class GsonUtils { private Gson gson; private GsonUtils() { gson = new Gson(); } private static class Holder { static final GsonUtils INSTANCE = new GsonUtils(); } public static GsonUtils getInstance() { return Holder.INSTANCE; } public Gson getGson() { return gson; } } – Mc Mike Dec 21 '16 at 06:43
  • Your singleton should have a private constructor. – shmosel Dec 21 '16 at 06:51

1 Answers1

0

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.

cringe
  • 13,401
  • 15
  • 69
  • 102