The Observer Pattern is a behavioral design pattern in which an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of state changes, typically by calling one of their methods. This pattern is used to define a one-to-many relationship between objects so that when one object changes state, all its dependents are notified and updated automatically.
Key components of the Observer Pattern include:
Subject (Observable): This is the object that is being observed. It maintains a list of observers and provides methods to add, remove, and notify observers.
Observer (Subscriber): These are the objects that are interested in being notified of changes in the subject. They implement an update method that is called by the subject when a change occurs.
Here's a simple example in C# to illustrate the Observer Pattern:
using System;
using System.Collections.Generic;
// Subject (Observable)
public class WeatherStation
{
private float temperature;
private List<>IObserver> observers = new List<>IObserver>>();
public void AddObserver(IObserver observer)
{
observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
public void SetTemperature(float temp)
{
temperature = temp;
NotifyObservers();
}
public void NotifyObservers()
{
foreach (var observer in observers)
{
observer.Update(temperature);
}
}
}
// Observer (Subscriber)
public interface IObserver
{
void Update(float temperature);
}
public class Display : IObserver
{
public void Update(float temperature)
{
Console.WriteLine($"Temperature is now {temperature} degrees.");
}
}
public class Logger : IObserver
{
public void Update(float temperature)
{
Console.WriteLine($"Logging temperature: {temperature}");
}
}
public class Program
{
public static void Main(string[] args)
{
WeatherStation weatherStation = new WeatherStation();
Display display = new Display();
Logger logger = new Logger();
weatherStation.AddObserver(display);
weatherStation.AddObserver(logger);
weatherStation.SetTemperature(25.5f); // Observers will be notified.
weatherStation.RemoveObserver(display); // Display is no longer interested.
weatherStation.SetTemperature(30.0f); // Only the Logger will be notified.
}
}
In this example, the WeatherStation is the subject that maintains a list of observers. When the temperature is updated, it notifies all registered observers, and they react accordingly. This allows for decoupling between the subject and its observers, making it easy to add or remove observers without modifying the subject's code.
0 Comments