这里是我带有弱引用的单例类。带有弱引用的Java单例
public class HandheldMapViewProvider {
private static WeakReference<HandheldMapViewProvider> mInstance = null;
private HandheldMapViewProvider(){
}
public static synchronized WeakReference<HandheldMapViewProvider> getInstance(){
if(mInstance == null){
mInstance = new WeakReference<HandheldMapViewProvider>(new HandheldMapViewProvider());
}
return mInstance;
}
public void onprint(String data){
Log.D("TAG",data)
}
}
上述类的用法如下。
private WeakReference<HandheldMapViewProvider> hereMapViewProvider;
public void onprint(){
hereMapViewProvider = HandheldMapViewProvider.getInstance();
hereMapViewProvider.get().onprint("somevalue");
}
虽然第一次调用onprint方法的应用程序有时因get()为空而崩溃。
任何想法,我做错了。它并没有一直发生。
解决方法如下。
public static synchronized HandheldMapViewProvider getInstance(){
HandheldMapViewProvider mapProvider = mInstance == null ? null :mInstance.get();
if(mapProvider == null){
mInstance = new WeakReference<HandheldMapViewProvider>(mapProvider =new HandheldMapViewProvider());
}
return mapProvider;
}
您的主要错误是摆脱了singelton模式摆在首位。 https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons –
从哪里调用最后一段代码? – 2017-07-17 13:19:35
@EnamulHaque来自活动。大多数相同的代码是完美的。有一段时间我变得空了。 –