Observer
- Use this pattern when the state of an object changes, you want to notify other objects about the changes
- Whenever subject/observable changes, observers get notified
- Also known as Publish Subscribe
Classical Structure
Scenario
- Build an app, whenever Datasource object changes notify SpreadSheet and Chart objects
Solution
using System;
using System.Collections.Generic;
public interface IObserver
{
void Notify();
}
public class SpreadSheet : IObserver
{
public void Notify()
{
Console.WriteLine("Spreadsheet got notified");
}
}
public class Chart: IObserver
{
public void Notify()
{
Console.WriteLine("Chart got notified");
}
}
public interface ISubject
{
void AddObserver(IObserver observer);
void RemoveObserver(IObserver observer);
void NotifyObservers();
}
public class DataSource : ISubject
{
List<IObserver> observers = new List<IObserver>();
private int value;
public int Value {
get => value;
set {
this.value = value;
NotifyObservers();
}
}
public void AddObserver(IObserver observer)
{
observers.Add(observer);
}
public void NotifyObservers()
{
foreach (IObserver observer in observers)
{
observer.Notify();
}
}
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
}
public class Program
{
public static void Main()
{
var spreadSheet = new SpreadSheet();
Chart chart = new Chart();
DataSource dataSource = new DataSource();
dataSource.AddObserver(spreadSheet);
dataSource.AddObserver(chart);
dataSource.Value = 10;
}
}
Example Structure
Communication Style
- Push
- Pull