December 19, 2004

Visitor pattern using reflection

As I said in this post, I think reflection is one of the most powerful features of languages like Java and C#. By using reflection, I can eliminate all of the redundancy from the my simple implementation of the visitor pattern. Admittedly, there might be some performance issues if I make heavy use of it.

Notice that there is absolutey no code needed in the modem classes to support their visitors. The modem base class does all the work. It uses reflection to search the visitor class for an appropriate accept method at runtime. Also, there is no need to implement visitor interfaces in the visitor class.


public abstract class Modem
{
public void Accept(object visitor)
{
Type modemType = GetType();
Type visitorType = visitor.GetType();
MethodBase acceptMethod = visitorType.GetMethod("Visit",
BindingFlags.Public BindingFlags.Instance, null,
new Type[] { modemType }, null);
if (acceptMethod != null)
{
acceptMethod.Invoke(visitor, new object[] { this });
}
else
{
// Throw exception or do nothing as appropriate
}
}
}

public class HayesModem : Modem
{
}

public class ZoomModem : Modem
{
}

public class ConfigureDOSModemVisitor
{
public void Visit(HayesModem modem)
{ }

public void Visit(ZoomModem modem)
{ }
}


Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?