In a previous blog post, we illustrated how to implement a Visitor pattern on top of the DocMaker 3.1 API.
This approach allowed to quickly define new document operations without needing to worry about the details of the
Document data structure.
With DocMaker 3.2, it becomes even easier to implement document visitors because the Visitor pattern has now been
implemented as part of the public API. Both the IVisitor interface and the DefaultVisitor
implementation are defined within the Adam.DocMaker.Core namespace. Each relevant class in the
API implements an Accept method, allowing it to accept any visitor that implements the
IVisitor interface.
We will take a look at the same example as in our previous blog post, i.e. a visitor collecting all paragraph styles
that are actively being used in the document. This is what the implementation of our visitor looks like using DocMaker 3.2:
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
using Adam.DocMaker.Core;
using System.Collections.Generic;
using System.Linq;
namespace VisitorSample
{
public class CollectParagraphStylesVisitor : DefaultVisitor
{
private readonly List<ParagraphStyle> _styles = new List<ParagraphStyle>();
public IEnumerable<ParagraphStyle> CollectedStyles
{
get
{
return _styles.Distinct();
}
}
public override bool Visit(Paragraph paragraph)
{
_styles.Add(paragraph.ParagraphStyle);
return true;
}
}
}
|
This is pretty much the same code we used before. The main difference is that the
DefaultVisitor base
class is now implemented as part of the DocMaker API. Also note that the
Visit method returns a boolean
value designating whether the items in the paragraph should be visited by the visitor. In this case we return
true because a paragraph may contain tables with more paragraphs.
The code for visiting a document is also identical to the code we used before:
| C# |
1
2
3
4
5
6
|
public static IEnumerable<ParagraphStyle> GetActiveParagraphStyles(Document document)
{
CollectParagraphStylesVisitor visitor = new CollectParagraphStylesVisitor();
document.Accept(visitor);
return visitor.CollectedStyles;
}
|
Here the only difference is that the
Accept method is no longer an extension method but is instead
implemented directly in the
Document class. With DocMaker 3.2, you can implement document visitors
just like you could before, but you no longer need to implement the Visitor pattern yourself.