Visitor Pattern
Summary: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Sample Code
Code
public abstract class Element
{
public abstract void Accept(IVisitor visitor);
}
public class Filter : Element
{
public string Name { get; set; }
public double Exposure { get; set; }
public double Contrast { get; set; }
public double Saturation { get; set; }
public Filter(string name, double exposure, double contrast, double saturation)
{
this.Name = name;
this.Exposure = exposure;
this.Contrast = contrast;
this.Saturation = saturation;
}
public override void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
public class Filters
{
private List<Filter> _filters = new List<Filter>();
public void Attach(Filter filter)
{
_filters.Add(filter);
}
public void Detach(Filter filter)
{
_filters.Remove(filter);
}
public void Accept(IVisitor visitor)
{
foreach (Filter f in _filters)
{
f.Accept(visitor);
}
Console.WriteLine();
}
}
public class Impact : Filter
{
public Impact() : base("Impact", 0, 1, 1) { }
}
public class Burn : Filter
{
public Burn() : base("Brighten", 1, 0, 0) { }
}
public class Dodge : Filter
{
public Dodge() : base("Impact", -1, 0, 0) { }
}
public interface IVisitor
{
void Visit(Element element);
}
public class CanonCorrectionVisitor : IVisitor
{
public void Visit(Element element)
{
Filter filter = element as Filter;
filter.Exposure *= -1.01;
filter.Contrast *= 1.01;
filter.Saturation *= 1.02;
Console.WriteLine("{0} {1}'s new configuration: exposure {2}, contrast {3}, saturation {4}",
filter.GetType().Name, filter.Name, filter.Exposure, filter.Contrast, filter.Saturation);
}
}
public class NikonCorrectionVisitor : IVisitor
{
public void Visit(Element element)
{
Filter filter = element as Filter;
filter.Contrast *= 1.02;
filter.Saturation *= 1.01;
Console.WriteLine("{0} {1}'s new configuration: exposure {2}, contrast {3}, saturation {4}",
filter.GetType().Name, filter.Name, filter.Exposure, filter.Contrast, filter.Saturation);
}
}
Usage
Filters f = new Filters();
f.Attach(new Impact());
f.Attach(new Burn());
f.Attach(new Dodge());
f.Accept(new CanonCorrectionVisitor());
Output
Impact Impact's new configuration: exposure -0, contrast 1,01, saturation 1,02
Burn Brighten's new configuration: exposure -1,01, contrast 0, saturation 0
Dodge Impact's new configuration: exposure 1,01, contrast 0, saturation 0
Comments
Post a Comment