单例类的多个实例......非常奇怪的行为

时间:2014-01-07 18:33:57

标签: java android singleton

我有一个实现Singleton模式的类。我需要一个Activity和一个片段(由活动托管)中的这个类的实例。

奇怪的是,如果活动是第一个创建单例类的实例,当我尝试从片段中检索该实例时,它会创建另一个实例......

以下是单例类的代码:

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()方法的所有调用都是在主线程上进行的。

2 个答案:

答案 0 :(得分:0)

首先,您的代码甚至没有编译

 map.put(k,v); // not add

第二次,我在构造函数中添加了println()

private HashMap<String, String> map;
private Singleton() {
    System.out.println("Singleton Constructor");
    map = new HashMap<String, String>();
}

第三次,我测试了它 -

public static void main(String[] args) {
    Singleton one = Singleton.getInstance();
    Singleton two = Singleton.getInstance();
    if (one == two) {
        System.out.println("One instance");
    }
}

结果

Singleton Constructor
One instance

如果您对错误提起诉讼,请发布您的实际代码(因为您的代码明显不正确)。

答案 1 :(得分:0)

正如您所说,您的代码不是线程安全的。除非Singleton实例化的代价很高,否则只需先预先设置它。

class Singleton {
    private static Singleton instance = new Singleton();