Observable Pattern
Summary: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically..
Sample Code
Code
public class DigitalCamera
{
public event EventHandler PictureTaken;
public void TakePicture()
{
System.Console.WriteLine("Taking picture.");
PictureTaken?.Invoke(this, EventArgs.Empty);
}
}
public class CameraSensorUtilities
{
public void PictureTakenEventHandler(object sender, EventArgs args)
{
System.Console.WriteLine("Cleaning digital sensor.");
}
}
public class SystemCounters
{
public void PictureTakenEventHandler(object sender, EventArgs args)
{
System.Console.WriteLine("Updating camera counters.");
}
}
Usage
var digitalCamera = new DigitalCamera();
var sensorUtils = new CameraSensorUtilities();
var counters = new SystemCounters();
digitalCamera.PictureTaken += sensorUtils.PictureTakenEventHandler;
digitalCamera.PictureTaken += counters.PictureTakenEventHandler;
digitalCamera.TakePicture();
Output
Taking picture.
Cleaning digital sensor.
Updating camera counters.
Comments
Post a Comment