有谁能看出我的单身人士班级是否合适?

时间:2016-12-21 06:35:26

标签: java android singleton

public class GsonUtils {

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

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

全部;

1 个答案:

答案 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