希望有一个简单的问题。我正在考虑实现一个拥有多个集合和HashMaps的类的最佳方式,其中类需要知道它们何时被修改以外的类 - 即添加/删除/更改的项目。每个集合/散列映射现在都需要在我的课堂中作为公共获取者公开。
所以我的基本类看起来如下...
public class MyClass {
protected final HashMap<String, String> _values = new HashMap<String, String>();
protected final ArrayList<MyOtherClass> _other = new ArrayList<MyOtherClass>();
protected final ArrayList<MyOtherClass2> _other2 = new ArrayList<MyOtherClass2>();
// ... implementation
public HashMap<String, String> getValues() {
return _values;
}
public ArrayList<MyOtherClass> getMyOtherClassList() {
return _other;
}
public ArrayList<MyOtherClass2> getMyOtherClassList2() {
return _other2;
}
public String getContent() {
// build the content based on other/other2...
StringBuilder sb = new StringBuilder();
// iterate through both collections to build content...
// ...
return sb.toString();
}
}
public getMyOtherClass {
public String name; // has getter and setter
public String value; // has getter and setter
}
public getMyOtherClass2 {
public String name; // has getter and setter
public String value; // has getter and setter
public String somethingElse; // has getter and setter
}
我想基于内容的长度,即 -
_values.add("Length", getContent().length);
所以添加一个键/值对_values根据添加到_other和_other2的内容,长度值是动态的。
这个问题暴露了_values和_other与公共getter是类外的任何东西都可以修改它们。课程将不知道项目是否已被修改。
我能想到的一些解决方案是使collection/hashmap只读 - 但是这会引发一个运行时异常 - 如果是这种情况,我希望编译器指出它们是只读的并且抛出一个例外,但我不知道这是否可能。
另一种方法是为每个集合/地图添加一个add/remove并相应地更新Length属性 - 但是,如果MyOtherClass中的值发生更改,MyClass仍然不知道它。
或者编写我自己的Hashmap/List/Collection来确定何时添加/删除项目,并且可能在getMyOtherClass,getMyOtherClass2上具有属性更改侦听器。
任何漂亮的解决方案呢?
感谢,
Andez
丹,好点。我手动复制和粘贴我的示例类,所以appologies。但是List <>也是一个接口;-) – Andez 2012-08-17 12:39:15