Understanding Visitor Pattern

Posted by Nezreli on Programmers See other posts from Programmers or by Nezreli
Published on 2013-10-23T12:38:33Z Indexed on 2013/10/23 16:08 UTC
Read the original article Hit count: 339

I have a hierarchy of classes that represents GUI controls. Something like this:

Control->ContainerControl->Form

I have to implement a series of algoritms that work with objects doing various stuff and I'm thinking that Visitor pattern would be the cleanest solution. Let take for example an algorithm which creates a Xml representaion of a hierarchy of objects. Using 'classic' approach I would do this:

public abstract class Control
{
    public virtual XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = document.CreateElement(this.GetType().Name);
        // Create element, fill it with attributes declared with control
        return xml;
    }
}

public abstract class ContainerControl : Control
{
    public override XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = base.ToXML(document);
        // Use forech to fill XmlElement with child XmlElements
        return xml;
    }
}

public class Form : ContainerControl
{
    public override XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = base.ToXML(document);
        // Fill remaining elements declared in Form class
        return xml;
    }
}

But I'm not sure how to do this with visitor pattern. This is the basic implementation:

public class ToXmlVisitor : IVisitor
{
    public void Visit(Form form)
    {
    }
}

Since even the abstract classes help with implementation I'm not sure how to do that properly in ToXmlVisitor. Perhaps there is a better solution to this problem. The reason that I'm considering Visitor pattern is that some algorithms will need references not available in project where the classes are implemented and there is a number of different algorithms so I'm avoiding large classes.

Any thoughts are welcome.

© Programmers or respective owner

Related posts about c#

Related posts about design-patterns