observer CurrentConditionsDisplay

This commit is contained in:
Alexander Zhirov 2022-11-11 03:03:18 +03:00
parent ddbfb4820c
commit 8170c93255
6 changed files with 121 additions and 0 deletions

14
observer/app.d Normal file
View File

@ -0,0 +1,14 @@
module observer.app;
import observer.weatherdata;
import observer.currentconditionsdisplay;
void main()
{
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}

View File

@ -0,0 +1,31 @@
module observer.currentconditionsdisplay;
import observer.displayelement;
import observer.observer;
import observer.weatherdata;
import std.stdio : writeln;
import std.format : format;
class CurrentConditionsDisplay : Observer, DisplayElement
{
private:
float temperature;
float humidity;
WeatherData weatherData;
public:
this(WeatherData weatherData)
{
weatherData.registerObserver(this);
}
override void update(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
display();
}
override void display()
{
writeln("Current conditions: %3.1f".format(temperature), "F degrees and %3.1f%% humidity".format(humidity));
}
}

View File

@ -0,0 +1,6 @@
module observer.displayelement;
interface DisplayElement
{
void display();
}

6
observer/observer.d Normal file
View File

@ -0,0 +1,6 @@
module observer.observer;
interface Observer
{
void update(float temp, float humidity, float pressure);
}

9
observer/subject.d Normal file
View File

@ -0,0 +1,9 @@
module observer.subject;
import observer.observer;
interface Subject
{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}

View File

@ -1,2 +1,57 @@
module observer.weatherdata; module observer.weatherdata;
import observer.subject;
import observer.observer;
import std.algorithm : remove, countUntil;
class WeatherData : Subject
{
private:
Observer[] observers;
float temperature, humidity, pressure;
public:
override void registerObserver(Observer o)
{
observers ~= o;
}
override void removeObserver(Observer o)
{
observers.remove(observers.countUntil(o));
}
override void notifyObservers()
{
foreach (Observer o; observers)
{
o.update(temperature, humidity, pressure);
}
}
void measurementsChanged()
{
notifyObservers();
}
void setMeasurements(float temperature, float humidity, float pressure)
{
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
@property float getTemperature()
{
return temperature;
}
@property float getHumidity()
{
return humidity;
}
@property float getPressure()
{
return pressure;
}
}