// AvgTemp.java
public abstract class AvgTemp {
// This function receives nottification from other Temperature Sensors
public AvgTemp() {
}
public void notifyReceived(String eventName, Object arg) {
if (eventName.equals("temperatureMeasurement"))
{
onNewtemperatureMeasurement((TempStruct) arg);
}
}
public abstract void onNewtemperatureMeasurement(TempStruct tempStruct);
}
For receiving notifications, AvgTemp.java file has to subscribe to a temperature sensor. It means I have to call subscribetemperatureMeasurement().
Now, my question is “Where should I call subscribetemperatureMeasurement() in AvgTemp.java file, so I can get notification from Sensor?”
Should I call subscribetemperatureMeasurement() function in the constructor of the AvgTemp class or in somewhere else?
Looks like your question is missing
Sensorskeleton, I guess it looks like this:and you have a choice between:
or (somewhere outside):
The former approach has several drawbacks:
introduces unnecessary coupling from
AvgTemptoSensorwhat if you want to subscribe to several sensors, you provide first one as a constructor argument and the remaining using the latter approach?
thisreference escapes from the constructor, very bad, yournotifyReceivedmight get called before the object is fully initialized (especially because this is anabstractclass)the
AvgTempcannot live without aSensorwhich seems to strict and makes testing harder (mocking/stubbing required)