Object作为Singleton类Java中的实例变量

时间:2016-04-30 19:37:32

标签: java android object singleton

我希望在整个应用程序中维护MyModel类的单个实例。所以我创建了一个类似于:

的Singleton类
public class MySingleton {

    private MySingleton () {}

    public MyModel getMyModel() {
        return myModel;;
    }

    public void setEmotionRecord(EmotionRecord emotionRecord) {
        this.emotionRecord = emotionRecord;
    }

    private static MySingleton instance;

    private MyModel myModel = new MyModel();


    public static synchronized MySingleton getInstance() {

        if (instance == null) {

            instance = new MySingleton ();
        }

        return instance;
    }
}

MyModel是一个模型类,类似于:

 public class MyModel {
    int a;
    String b;
    private MyModel() {}
//....Getter Setter of a and b
}

我可以认为它是一个很好的Singleton类吗?

0 个答案:

没有答案