Wednesday, November 19, 2008

Genric implementation of Visitor pattern

As explained in the first part of this article series generic implementation of Visitor pattern involves usage of delegates and anonymous methods.

The Visit method invokes the algorithm processing using anonymous methods.

public class GenericVisitor

{

private IEnumerable _enumerableT;

public GenericVisitor(IEnumerable elements)

{

_enumerableT = elements;

}

public void Visit(Action callback)

{

foreach (T element in _enumerableT)

{

callback.Invoke(element);

}

}

}

Which can be used as

GenericVisitor<IElement> carVisitor = new GenericVisitor<IElement>(car.carElements);

carVisitor.Visit(delegate(IElement element)

{

Console.WriteLine(element.ToString());

});

No comments: