Observer Pattern
From Logic Wiki
Contents
Definition
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
What problems can the Observer design pattern solve?
The Observer pattern addresses the following problems:
- A one-to-many dependency between objects should be defined without making the objects tightly coupled.
- It should be ensured that when one object changes state an open-ended number of dependent objects are updated automatically.
- It should be possible that one object can notify an open-ended number of other objects.
Interface of Observable (Subject)
interface IObservable{
add(IObserver o)
remove(IObserver o)
notify()
}
Concrete Class implementing Observable Interface
class WeatherStation:IObservable{
private List<IObserver> Observers = new List<IObserver>();
private int temprature = 0 ;
...
public void Add(IObserver o){
this.Observers.Add(o)
}
public void Notify(){
foreach(IObserver o in this.Observers{
o.Update();
}
}
public int GetTempreture(){
return this.temprature;
}
}
Interface of Observer
Intervace IObserver{
Update();
}
Concrete Implementation of Observer
class PhoneDisplay:IObserver{
private WeatherStation _weatherStation;
public PhoneDisplay(WeatherStation weatherStation){
_weatherStation = weatherStation
}
public void Update(){
this.station.GetTemprature();
}
Comments to the code above
Instead of creating interfaces for different signatures of update method, we should create a generic interface that has void Update(T value) and IObservable with void Add(IObservable<T> observer).