A use case of the visitor pattern - document format conversion

A use case of the visitor pattern - document format conversion

Suppose we are developing a document editor that supports many different document elements (such as paragraphs, pictures, tables, etc.), and now we need to add a function - export the document to HTML or Markdown format.

This is a typical application scenario of the visitor pattern: the object structure (document elements) is stable, but the operations (export to different formats) change frequently. Also, we need to perform operations on the entire document structure, but don't want to write a lot of irrelevant if-else statements in each element class.

The following is the simplified code implementation:

java
// abstract element
interface DocumentElement { void accept(FormatVisitor visitor); }

// 具体元素
class Paragraph implements DocumentElement {
public void accept(FormatVisitor visitor) {
visitor.visit(this);
}
}

class Image implements DocumentElement {
public void accept(FormatVisitor visitor) {
visitor.visit(this);
}
}

// visitor
interface interface FormatVisitor { void visit(Paragraph paragraph); void visit(Image image); }


// specific visitor
class HtmlFormatVisitor implements FormatVisitor { public void visit(Paragraph paragraph) { // convert paragraph to HTML format }


public void visit(Image image) {
    // 将图片转换为 HTML 格式
}

}

class MarkdownFormatVisitor implements FormatVisitor { public void visit(Paragraph paragraph) { // convert paragraph to Markdown format }


public void visit(Image image) {
    // 将图片转换为 Markdown 格式
}

}
In the above code, DocumentElement is an abstract element, and Paragraph and Image are concrete elements. The abstract element defines an accept method that receives a visitor object as a parameter. Concrete elements implement the accept method and call the visitor's visit method to perform format conversion.

Then, we defined two specific visitors, HtmlFormatVisitor and MarkdownFormatVisitor, to realize the function of exporting to HTML and Markdown formats respectively. When we need to add a new format (such as PDF), we only need to define a new visitor without modifying the code of any element class.

Guess you like

Origin blog.csdn.net/u014244856/article/details/132687227