Null Object Pattern
Summary: A no-op object that conforms to the required interface, satisfying a dependency requirement of some other object.
Sample Code
Code
public class Photo
{
public int Exposure { get; set; } = 0;
public int Saturation { get; set; } = 0;
public int Contrast { get; set; } = 0;
public override string ToString()
{
return $"Exposure: {Exposure}, Contrast: {Contrast}, Saturation: {Saturation}";
}
}
public class PhotoEditor
{
public void ApplyFilter(Photo photo, IFilter filter) => filter.ApplyFilter(photo);
}
public interface IFilter
{
void ApplyFilter(Photo photo);
}
public class ImpactFilter : IFilter
{
public void ApplyFilter(Photo photo)
{
photo.Saturation += 1;
photo.Contrast += 2;
}
}
public class NullFilter : IFilter
{
public void ApplyFilter(Photo photo) { }
}
Usage
var photo = new Photo();
System.Console.WriteLine(photo);
var photoEditor = new PhotoEditor();
photoEditor.ApplyFilter(photo, new ImpactFilter());
System.Console.WriteLine(photo);
photoEditor.ApplyFilter(photo, new NullFilter());
System.Console.WriteLine(photo);
Output
Exposure: 0, Contrast: 0, Saturation: 0
Exposure: 0, Contrast: 2, Saturation: 1
Exposure: 0, Contrast: 2, Saturation: 1
Comments
Post a Comment