This repository has been archived on 2022-11-20. You can view files and clone it, but cannot push or open issues or pull requests.
patterns/observer/weatherdata.d

61 lines
1.3 KiB
D
Raw Normal View History

2022-11-10 13:28:55 +00:00
module observer.weatherdata;
2022-11-11 07:56:59 +00:00
2022-11-11 00:03:18 +00:00
import observer.subject;
import observer.observer;
import std.algorithm : remove, countUntil;
2022-11-10 13:28:55 +00:00
2022-11-11 00:03:18 +00:00
class WeatherData : Subject
{
private:
Observer[] observers;
float temperature, humidity, pressure;
public:
override void registerObserver(Observer o)
{
observers ~= o;
}
override void removeObserver(Observer o)
{
2022-11-11 07:22:38 +00:00
// Вызовет ошибку в случае отсутствия элемента в массиве после его поиска
// observers = observers.remove(observers.countUntil(o));
observers = remove!(current => current == o)(observers);
2022-11-11 00:03:18 +00:00
}
override void notifyObservers()
{
foreach (Observer o; observers)
{
2022-11-11 07:56:59 +00:00
o.update();
2022-11-11 00:03:18 +00:00
}
}
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;
}
}