我最初的单身课程就像这样
private static MqttHandler instance = new MqttHandler();
private MqttHandler(){};
public MqttHandler getInstance(){
return instance;
}
现在在一部手机中,它按预期工作,但在另一部手机中,似乎它创建了许多实例,因为每当我尝试记录某些内容时,它都会多次记录。我不知道为什么。 我第二次尝试使用这个
private MqttHandler instance;
private MqttHandler(){};
public MqttHandler getInstance(){
if(instance==null) instance == new MqttHandler();
return instance;
}
似乎工作,至少现在,不确定它是否会在以后崩溃,这是否意味着,在我的第一个方法中,每当我返回实例时,它都在调用
new MqttHandler();
因此一直在创建新实例?为什么它会在一台设备上正常工作,然后完全拒绝另一台设备?
答案 0 :(得分:0)
两者都应该具有相同的效果。当然,后者的好处是在实际需要之前不会创建对象,但要注意,由于并发调用getInstance,可能会多次创建对象。
另外,你需要一个"静态" getInstance中的声明(否则你必须创建一个实例来获取单例)。
答案 1 :(得分:0)
这是实现简单singleton
:
// It must be static and final to prevent later modification
private static final MqttHandler INSTANCE = new MqttHandler();
// The constructor must be private to prevent external instantiation
private MqttHandler(){};
// The public static method allowing to get the instance
public static MqttHandler getInstance() {
return INSTANCE;
}
您的第二种方法仅适用于单线程应用程序,因为如果您使用多个并发线程同时调用getInstance
,它将创建对象的多个实例,以便破坏单例的合约。所以如果你需要正确地懒惰创建你的单身人士,这里是如何继续:
// The constructor must be private to prevent external instantiation
private MqttHandler(){};
// The public static method allowing to get the instance
public static MqttHandler getInstance() {
return MqttHandlerHolder.INSTANCE;
}
/**
* The static inner class responsible for creating your instance only on demand,
* because the static fields of a class are only initialized when the class
* is explicitly called, this rule is also applicable to inner static class
* So here INSTANCE will be created only when MqttHandlerHolder.INSTANCE will be called
*/
private static class MqttHandlerHolder {
private static final MqttHandler INSTANCE = new MqttHandler();
}