Ch2Weather: add TemperatureStatsDisplay

This commit is contained in:
2025-11-02 14:52:19 +01:00
parent 3c2948a5d1
commit 778fec0b34
2 changed files with 34 additions and 0 deletions

View File

@@ -92,4 +92,37 @@ public class HeatIndexDisplay : IWeatherObserver, IWeatherDisplay {
var heatIndex = ComputeHeatIndex(_weatherRecord.Temperature, _weatherRecord.Humidity);
Console.WriteLine($"Heat Index is {heatIndex}");
}
}
public class TemperatureStatsDisplay : IWeatherObserver, IWeatherDisplay {
private IWeatherSubject _subject;
private double _n = 0;
private double _avg = 0;
private double _min = 0;
private double _max = 0;
public TemperatureStatsDisplay(IWeatherSubject subject) {
_subject = subject;
subject.Subscribe(this);
}
public void Update(WeatherRecord wr) {
var temp = wr.Temperature;
if (_n == 0) {
_n = 1;
_avg = temp;
_min = temp;
_max = temp;
} else {
_min = double.Min(_min, temp);
_max = double.Max(_max, temp);
_avg = (_avg * _n + temp) / (_n + 1);
_n += 1;
}
Display();
}
public void Display() {
Console.WriteLine($"Avg/Max/Min Temperature: {_avg}/{_max}/{_min}");
}
}