我正在做一些事情,我需要一个观察者或监听器,当地图的EntrySet发生变化时会做出反应。 我真的不知道为什么我的观察者没有反应。
首先,我有一个应该是Observable对象的StorageModel:
public class StorageModel extends Observable{
public SortedMap<String, Integer> coMap;
public SortedMap<String, Integer> co2Map;
private String id;
public StorageModel(String id) {
this.id = id;
coMap = new TreeMap<>(Collections.reverseOrder());
co2Map = new TreeMap<>(Collections.reverseOrder());
Observer storageObserver = new Classificator(coMap, co2Map);
addObserver(storageObserver);
}
public void writeToCoMap(SortedMap<String, Integer> map, String str, int val){
map.put(str, val);
listenToChangesInCo(map);
}
public void writeToCo2Map(SortedMap<String, Integer> map, String str, int val){
map.put(str, val);
listenToChangesInCo2(map);
}
public void listenToChangesInCo(SortedMap<String, Integer> map){
setChanged();
this.coMap = map;
notifyObservers(coMap.entrySet());
}
public void listenToChangesInCo2(SortedMap<String, Integer> map){
setChanged();
this.co2Map = map;
notifyObservers(co2Map.entrySet());
}
}
public class Classificator implements ConstantFields, Runnable, Observer{
static Set<MeasurementModel> classifiedWaspmotes = new HashSet<>();
static Set<StorageModel> waspmotes = new HashSet<>();
private static SortedMap<String, Integer> coMap = new TreeMap<>();
private static SortedMap<String, Integer> co2Map = new TreeMap<>();
private static StorageModel observerableStorageModel;
public Classificator(SortedMap<String, Integer> coMap, SortedMap<String, Integer> co2Map){
this.coMap = coMap;
this.co2Map = co2Map;
}
@Override
public void update(Observable observable, Object o) {
observerableStorageModel = (StorageModel) observable;
System.out.println("reacting to changes");
}
}
在另一个处理来自无线模块的传入数据的功能中 我想将已处理的数据写入现有地图,这是观察者应该做出反应的地方。
public void truncateMessage(String msg, String nodeID, SortedMap<String, Integer> coMap, SortedMap<String, Integer> co2map) throws InterruptedException {
StorageModel mod = new StorageModel();
mod.setId(nodeID);
String message = msg;
List<Integer> coValues = new ArrayList<>();
List<Integer> co2Values = new ArrayList<>();
String idStr = message.substring(0, 3);
String digits = "";
if(idStr.equals("CO_")){
System.out.println("co found");
System.out.println(message);
message = cleanseMessage(message);
System.out.println(message);
addValuesToList(coValues, message);
System.out.println("values found in list");
System.out.println(coValues);
for(int i: coValues){
//coMap.put(sdf.format(new Date()), i);
mod.writeToCoMap(coMap, sdf.format(new Date()), i);
Thread.sleep(100);
}
}
我真的很感谢你的帮助。
干杯