static void Main(string[] args) { /* * More info: https://manski.net/2013/05/the-visitor-pattern-explained * What problems can the Visitor design pattern solve? * * It should be possible to define a new operation for (some) classe * s of an object structure without changing the classes. * * When new operations are needed frequently and the object structure consists of many unrelated classes, * it's inflexible to add new subclasses each time a new operation is required because "[..] distributing * all these operations across the various node classes leads to a system that's hard to understand, maintain, and change." * */ var doc = new Document(new PlainText { Text = "Plain" }, new Hyperlink { Text = "Hyper", Url = "Link" }); var visitor = new HtmlVisitor(); doc.Accept(visitor); Console.WriteLine($"Plain text plus Hyperlink {visitor.Output}"); var doc2 = new Document(new PlainText { Text = "Plain" }, new Hyperlink { Text = "Hyper", Url = "Link" }); var visitor2 = new LatexVisitor(); doc.Accept(visitor); Console.WriteLine($"Plain text plus Hyperlink {visitor.Output}"); }
public void TestVisitor() { var document = new Document(); document.AddPart(new BoldText("This is bold text.")); document.AddPart(new PlainText("This is plain text.")); document.AddPart(new Hyperlink("This is hyperlink.", "http://www.example.com")); var htmlVisitor = new HtmlVisitor(); document.Accept(htmlVisitor); Assert.That( htmlVisitor.Output, Is.EqualTo("<b>This is bold text.</b>This is plain text.<a href=\"http://www.example.com\">This is hyperlink.</a>")); var latexVisitor = new LatexVisitor(); document.Accept(latexVisitor); Assert.That( latexVisitor.Output, Is.EqualTo("\\textbf{This is bold text.}This is plain text.\\href{http://www.example.com}{This is hyperlink.}")); }
public static string ToLaTeX(this DocumentPart part) { Visitor visitor = new LatexVisitor(); return(visitor.Visit(part)); }