Head First Design Patterns: The Observer Pattern

OO Principles: Strive for loosely coupled designs between objects that interact.

OO Patterns: Observer – defines a one to many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Subjects/Observables update Observers using a common interface.

public interface ISubject
{
void RegisterObserver(IObserver observer);
void RemoveObserver(IObserver observer);
void NotifyObservers();
}

public class WeatherData : ISubject
{
private List<IObserver> _observers = new List<IObserver>();
private float _temperature;
private float _humidity;
private float _pressure;

public void RegisterObserver(IObserver observer)
{
_observers.Add(observer);
}

public void RemoveObserver(IObserver observer)
{
_observers.Remove(observer);
}

public void NotifyObservers()
{
foreach (IObserver observer in _observers)
{
observer.Update(_temperature, _humidity, _pressure);
}
}

public void MeasurementsChanged()
{
NotifyObservers();
}

public void SetMeasurements(float temperature, float humidity, float pressure)
{
this._temperature = temperature;
this._humidity = humidity;
this._pressure = pressure;
MeasurementsChanged();
}
}

 

public interface IObserver
{
void Update(float temperature, float humidity, float pressure);
}

public interface IDisplayElement
{
void Display();
}

public class CurrentConditionsDisplay : IObserver, IDisplayElement
{
private float _temperature;
private float _humidity;
private ISubject _weatherData;

public CurrentConditionsDisplay(ISubject weatherData)
{
this._weatherData = weatherData;
weatherData.RegisterObserver(this);
}

public void Update(float temperature, float humidity, float pressure)
{
this._temperature = temperature;
this._humidity = humidity;
Display();
}

public void Display()
{
Console.WriteLine(“Current conditions: ” + _temperature
+ “F degrees and ” + _humidity + “% humidity”);
}
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s