가상 스테이션
다이어그램
IDisplay.cs
1
2
3
4
public interface IDisplay
{
void Display();
}
IObserver.cs
1
2
3
4
public interface IObserver
{
void Update();
}
ISubject.cs
1
2
3
4
5
6
public interface ISubject
{
void RegisterObserver(IObserver observer);
void RemoveObserver(IObserver observer);
void NotifyObserver();
}
WeatherData.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class WeatherData : ISubject
{
private readonly List<IObserver> _observers = new List<IObserver>();
public float Temperature { get; set; }
public float Humidity { get; set; }
public float Pressure { get; set; }
public void MeasurementsChanged()
{
NotifyObserver();
}
public void RegisterObserver(IObserver observer)
{
_observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
_observers.Remove(observer);
}
public void NotifyObserver()
{
_observers.ForEach(item => item.Update());
}
public void SetMeasurements(float temp, float humidity, float pressure)
{
Temperature = temp;
Humidity = humidity;
Pressure = pressure;
MeasurementsChanged();
}
}
CurrentConditionsDisplay.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class CurrentConditionsDisplay : IObserver,IDisplay
{
private float _temperature;
private float _humidity;
private readonly WeatherData _weatherData;
public CurrentConditionsDisplay(WeatherData weatherData)
{
_weatherData = weatherData;
_weatherData.RegisterObserver(this);
}
public void Display()
{
Console.WriteLine($"Current conditions : temperature : {_temperature}, humidity : {_humidity}%");
}
public void Update()
{
_temperature = _weatherData.Temperature;
_humidity = _weatherData.Humidity;
Display();
}
}
나머지 코드는 git에…
git 주소 : Design Patterns with CS