1

我目前正在编写一个 Android 应用程序,并且我有一个关于何时使用静态方法/字段的更高级别的问题。

我的应用程序跟踪不同活动的时间使用情况,每个活动都是一个类的实例。我需要一个可以返回这个类的所有实例的方法。

像这样在我的 Activity 类中放置静态方法/字段是否是糟糕的设计:

static ArrayList<Activity> allInstances;    
public static void addToComprehensiveList(Activity a) {
    if(allInstances == null)
        allInstances = new ArrayList<Activity>();
    allInstances.add(a);
}
public static ArrayList<Activity> getComprehensiveList() {
    return allInstances;
}

这里正确的设计选择是什么?

4

2 回答 2

3

Keeping a static list of instances is a fairly safe and normal thing to do. The main gotchas have to do with when you add items to the list.

For example, if Activity has a nontrivial constructor that calls addToComprehensiveList(this) when it starts, then there are times when not-fully-initialized objects are in a publicly accessible list. If your program is single-threaded, this isn't too dangerous - unless the constructor later throws an exception, in which case the object is left in the list in a not-fully-initialized state.

A safe way around this is to create your instances in a factory method that adds the object to the list after it is created. Of course, if there are no subclasses, just adding to the list as the last statement in the constructor works fine.

The other danger here is that getComprehensiveList() returns a reference to its instance list, which means that client code could be modifying that list without your class knowing. Even if the client just iterates through the list, you would get a commodification exception if you create a new Activity during their iteration. A safer approach is to return a copy of the list.

于 2012-12-21T02:15:58.463 回答
-2

根据我在重压或内存使用情况下做这样的事情的经验:

static ArrayList<Activity> allInstances; 

不保证可用。VM 可以取消它,这就是 Singleton 可能更安全的原因。

于 2012-12-21T02:36:58.823 回答