简体   繁体   中英

Managing cleanup from views (rather than Activities)… Dangers of singleton pattern?

Coming from a non-Java background, I find myself writing a lot of View classes with extensive functionality (in an effort to be portable), that don't necessarily fit nicely into the Android FW setup as far as maintenance - for example, I might have a widget that does something on a interval that I want to stop and clean up when an Activity is paused/stopped/destroyed. Generally I can manage this by just calling a public method on the widget from the containing Activity, but A) sometimes this gets pretty deep, and having to create a public method to access a child in every parent can get ugly, and B) requires extra (uneeded?) attention.

I'm considering using an approach like a global delegate to manage this kind of thing, but have read a lot of warnings about this sort of approach - would something like the class that follows have any inherent flaws that I might be missing?

import java.util.HashMap;
import java.util.HashSet;

public class ActiveRegistry {

    private static final ActiveRegistry instance = new ActiveRegistry();
    public static ActiveRegistry getInstance(){
        return instance;
    }

    private HashMap<String, HashSet<Runnable>> registry = new HashMap<String, HashSet<Runnable>>();
    private ActiveRegistry(){

    }

    public void register(String key, Runnable runnable){
        if(!registry.containsKey(key)){
            HashSet<Runnable> list = new HashSet<Runnable>();
            registry.put(key, list);
        }
        HashSet<Runnable> list = registry.get(key);
        list.add(runnable);
    }

    public void execute(String key){
        if(registry.containsKey(key)){
            HashSet<Runnable> list = registry.get(key);
            for(Runnable runnable : list){
                runnable.run();
            }
        }
    }
}

Use might be something like...

  1. A View has something that needs to be cleaned up. On instantiation, register it... ActiveRegistry.getInstance().register("paused", someRunnableThatCleansUpStuff)
  2. Extend Activity so that onPause calls ActiveRegistry.getInstance().execute("paused");

You are doing way more work than you need to. Using Fragment s (from the support package , if you want to ensure backwards compatibility with older versions of android), will make your life a whole lot easier. Each fragment is embedded in an activity and has a lifecycle that is directly linked with its host activity's lifecycle. Using them should significantly reduce the complexity of your code, as most of what you are currently worrying about will be managed by the system instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM