/// <summary> /// When we receive a new reading, check all the observer clients to see if we need to send any threshold notifications /// </summary> /// <param name="sender">The sender themometer</param> /// <param name="e">The <see cref="NewReadingReceivedEventArgs"/> reading</param> private void _thermometer_OnNewReadingReceived(object sender, NewReadingReceivedEventArgs e) { foreach (var observation in _observations) { var t = IsThresholdReached(observation, e); var f = IsFirstReading(observation, e); var d = IsReadingDifferentThanLastOne(observation, e); // Ask subclass if we should send the notification, and keep the flow steps here (Template Method). if (IsThresholdReached(observation, e) && (IsFirstReading(observation, e) || (IsReadingDifferentThanLastOne(observation, e) && IsSensitivityVarianceMet(observation, e)))) { // Set the current temperature observation.Threshold.CurrentReading = e.Reading; // Notify observation.CallBack(observation.Threshold); // Update last notification temperature observation.Threshold.LastNotificationTemperature = e.Reading; } } }
protected bool IsSensitivityVarianceMet(ThresholdObservation observation, NewReadingReceivedEventArgs e) => Math.Abs(e.Reading - observation.Threshold.LastNotificationTemperature.Value) >= observation.Threshold.Sensitivity;
protected bool IsReadingDifferentThanLastOne(ThresholdObservation observation, NewReadingReceivedEventArgs e) => e.Reading != observation.Threshold.LastNotificationTemperature;
// Common business logic snippets to all protected bool IsFirstReading(ThresholdObservation observation, NewReadingReceivedEventArgs e) => !observation.Threshold.LastNotificationTemperature.HasValue;
/// <summary> /// Template method to ask the subclass if the threshold was reached /// </summary> /// <param name="observation">The observation with all the necessary info</param> /// <param name="e">The current reading received</param> /// <returns></returns> protected abstract bool IsThresholdReached(ThresholdObservation observation, NewReadingReceivedEventArgs e);
// Check if we've hit the threshold protected override bool IsThresholdReached(ThresholdObservation observation, NewReadingReceivedEventArgs e) => e.Reading >= observation.Threshold.Temperature;