从视图(而不是活动)管理清理..单例模式的危险


来自

非Java背景,我发现自己编写了很多具有广泛功能的View类(为了便于移植),就维护而言,这些类不一定适合Android FW设置 - 例如,我可能有一个小部件,它在一个时间间隔内执行某些操作,我想在活动暂停/停止/销毁时停止并清理。 通常,我可以通过从包含的活动中调用小部件上的公共方法来管理它,但是 A) 有时这变得非常深入,并且必须创建一个公共方法来访问每个父项中的子项可能会变得丑陋,并且 B) 需要额外的(不需要?

我正在考虑使用全局委托之类的方法来管理这种事情,但是已经阅读了很多关于这种方法的警告 - 像下面的类这样的东西是否有任何我可能遗漏的固有缺陷?

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();
            }
        }
    }
}

使用可能是这样的...

  1. View有一些东西需要清理。 在实例化时,注册它... ActiveRegistry.getInstance().register("paused", someRunnableThatCleansUpStuff)
  2. 扩展Activity,以便onPause呼叫ActiveRegistry.getInstance().execute("paused");

你正在做比你需要的更多的工作。使用 Fragment s(来自支持包,如果您想确保与旧版本的 android 向后兼容),将使您的生活更加轻松。每个片段都嵌入在一个活动中,并且具有与其主机活动的生命周期直接关联的生命周期。使用它们应该会显著降低代码的复杂性,因为您当前担心的大部分内容将由系统管理。

最新更新