Skip to main content

Chain of Responsibility

Chain of Responsibility Pattern 


Gamma Categorization: Structural Design 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

Problem: We want to create a proxy class to intercept the server connection.

Code

public class Photo
{
    public string Name { getset; }
    public int Exposure { getset; }
    public int Saturation { getset; }
    public int Contrast { getset; }

    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