I have a class Settings with static methods which I use to save and load my data. This is for example the Save() method:

public static void Save(SETTING_KEY key, String value)
{
    SharedPreferences sp = _context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();

    editor.putString(key.toString(), value);
    editor.commit();    
}

Now I'd like to make the class Settings observable. The problem is that extending my Settings-class from Observable does not work, as I don't instantiate this class as I only use its static methods.

Is there any easy way to make this static class observable?

有帮助吗?

解决方案

Add your own observer mechanism. Simple implementation below

public interface Observer {
    void onSettingsChanged(String key, String value);
}

private static Observer observer;
public static void setObserver(Observer observer_) {
    observer = observer_;
}

public static void Save(SETTING_KEY key, String value) {
    SharedPreferences sp = _context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();

    editor.putString(key.toString(), value);
    editor.commit();
    if (observer != null) {
        observer.onSettingsChanged(key, value);
    }
}

You could also use a List<Observer> if you need more than 1 and you can also use some sort of event bus (e.g. Otto) system to publish events without having to provide a direct observer mechanism.

其他提示

You could try using a Singleton pattern? (Java Singleton Pattern)

That way, you can extend observable.

You could combine a singleton with static methods.

class Settings extends Observable {
    private static Settings instance;
    private static synchronized Settings getInstance() {
        if(instance == null) {
            instance = new Settings();
        }
        return instance;
    }

    public static void Save(SETTING_KEY key, String value)
    {
        SharedPreferences sp = _context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString(key.toString(), value);
        editor.commit();
        getInstance().notifyObservers(value); // or whatever
    }

    // can't override addObserver with a static method, so make a new method instead
    public static void addObserverStatic(Observer observer) {
        getInstance().addObserver(observer);
    }
}

As others have said, static methods on a singleton is a bit naughty. Do it some other way if you can.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top