Posts

Showing posts from December, 2012

The Acyclic Visitor Pattern

Knock knock The visitor design pattern is a way to add new operations to a hierarchy of classes without having to change the hierarchy itself. For example, with a simple hierarchy of fruits, you can have an IFruitVisitor interface that operates on the different classes in the hierarchy (in C#): interface IFruitVisitor { void Visit(Apple apple); void Visit(Grape grape); } The hierarchy classes then accept the visitor and fulfil the double-dispatching necessary to call the right Visit method: abstract class Fruit { public abstract void Accept(IFruitVisitor visitor); } class Apple : Fruit { public override void Accept(IFruitVisitor visitor) { visitor.Visit(this); } } class Grape : Fruit { public int NumberOfGrapes { get; set; } public override void Accept(IFruitVisitor visitor) { visitor.Visit(this); } } Note how each Accept method looks the same but is actually dispatching to a different method in the visitor ( Visit(Apple) and Visit(Grape) ). ...