Изначальная реализация паттерна проектирования "Наблюдатель" (Observer) для погоды
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lb2
{
class Program
{
public static void Main()
{
WeatherData weatherData = new WeatherData();
CarrentConditionDisplay carrentDisplay = new CarrentConditionDisplay(weatherData);
//...
weatherData.setMeasurements(80, 65, 30.4);
weatherData.setMeasurements(82, 70, 29.2);
weatherData.setMeasurements(78, 90, 29.2);
Console.Read();
}
}
public interface Subject
{
public void registerObserver(Observer 0);
public void removeObserver(Observer 0);
public void notifyObservers();
}
public interface Observer
{
public void update(float temp, float hum, float press);
}
public interface DisplayElement
{
public void display();
}
public class WeatherData : Subject
{
// private string SubjectState { get; set; }
private ArrayList observers;
private float temp;
private float hum;
private float pressure;
public WeatherData()
{
observers = new ArrayList ();
}
public void registerObserver(Observer 0)
{
observers.Add(0);
}
public void removeObserver(Observer 0)
{
int i = observers.indexOF(0);
if (i>=0) observers.remove(i);
}
public void notifyObservers()
{
foreach (Observer obs in Observers)
Obs.opdate(temp, hum, pressure);
}
public void measurementsChanges()
{
notifyObservers();
}
public void SetMeasurements(float temp, float hum, float press);
{
this.temp = temp;
this.hum = hum;
this.pressure = press;
measurementsChanges();
}
//реализовать другие методы класса
public class CarrentConditionDisplay:Observer, DisplayElement
{
private float temper;
private float humid;
private Subject weatherData;
public CarrentConditionDisplay(Subject wData)
{
this.weatherData = wData;
wData.registerObserver(this);
}
public void update(float temp, float hum, float press)
{
this.temper = temp;
this.humid = hum;
Display();
}
public void Display()
{
System.Console.WriteLine("Текущие условия" + temper + "С и " + humid + "% влажности");
}
}
}