我有一個實現Singleton模式的類。我需要一個活動和一個片段中的這個類的實例(由活動託管)。單例類的多個實例......很奇怪的行爲
但奇怪的是,同樣如果活動是第一次創建單獨的類的實例,當我嘗試檢索它創建另一個實例的片段實例...
以下是singleton類的代碼:
public class NotificationCenter {
private NotificationCenter() {
}
// useless for this question
private class MyObservable extends Observable {
@Override
protected void setChanged() {
super.setChanged();
}
}
// useless for this question
private class MyObserver implements Observer {
String name;
Notificable notificable;
public MyObserver(String name, Notificable notificable) {
this.name = name;
this.notificable = notificable;
}
@Override
public void update(Observable observable, Object data) {
notificable.notificationReceived(name, data);
}
}
private static NotificationCenter defaultCenter = null;
private HashMap<String, MyObservable> observables;
public static synchronized NotificationCenter defaultCenter() {
if (defaultCenter==null) {
defaultCenter = new NotificationCenter();
defaultCenter.observables = new HashMap<String, MyObservable>();
}
return defaultCenter;
}
public void addObserver(String notification, Notificable notificable) {
MyObservable observable = observables.get(notification);
if (observable==null) {
observable = new MyObservable();
observables.put(notification, observable);
}
MyObserver observer = new MyObserver(notification, notificable);
observable.addObserver(observer);
}
public void removeObserver(String notification, Observer observer) {
MyObservable observable = observables.get(notification);
if (observable!=null) {
observable.deleteObserver(observer);
}
}
public void postNotification(String notification, final Object object) {
final MyObservable observable = observables.get(notification);
if (observable!=null) {
observable.setChanged();
observable.notifyObservers(object);
}
}
}
我必須考慮一些東西,我不? 所有對defaultCenter()方法的調用都在主線程上進行。
你怎麼知道它不同? –
,因爲我從調試器看到它從創建指令(instance = new Singleton();)傳遞兩次,並且因爲其他考慮因素。我確定它創建了兩次單例實例 – Massimo
除非你搞亂了類加載器,它只能是一個線程安全問題... – assylias