Chain of Responsibility Pattern
Summary: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Sample Code
Code
public class Photo
{
public string Name { get; set; }
public int Exposure { get; set; }
public int Saturation { get; set; }
public int Contrast { get; set; }
public Photo(string name)
{
this.Name = name;
this.Exposure = this.Saturation = this.Contrast = 0;
}
}
public class PhotoModifier
{
protected Photo photo;
protected PhotoModifier next;
public PhotoModifier(Photo photo)
{
this.photo = photo;
}
public void Add(PhotoModifier photoModifier)
{
if (next != null)
next.Add(photoModifier);
else
next = photoModifier;
}
public virtual void Handle() => next?.Handle();
}
public class AddOneStopExposure : PhotoModifier
{
public AddOneStopExposure(Photo photo) : base (photo) {}
public override void Handle()
{
System.Console.WriteLine("Increasing exposure.");
photo.Exposure += 1;
base.Handle();
}
}
public class AddContrast : PhotoModifier
{
public AddContrast(Photo photo) : base (photo) {}
public override void Handle()
{
System.Console.WriteLine("Increasing constrast.");
photo.Contrast += 1;
base.Handle();
}
}
Usage
var photo = new Photo("IMG_01");
var modifierBase = new PhotoModifier(photo);
modifierBase.Add(new AddOneStopExposure(photo));
modifierBase.Add(new AddContrast(photo));
modifierBase.Handle();
System.Console.WriteLine($"Photo: {photo.Name}, Exposure: {photo.Exposure}, Contrast: {photo.Contrast}, Saturation: {photo.Saturation}");
Output
Increasing exposure.Increasing constrast.
Photo: IMG_01, Exposure: 1, Contrast: 1, Saturation: 0
Comments
Post a Comment