Visitor Pattern Demo

Interfaces:

package VisitorPatternDemo; // Document interface interface Document { void accept(DocumentVisitor visitor); String getTitle(); }
package VisitorPatternDemo; // Visitor interface interface DocumentVisitor { void visit(TextDocument document); void visit(SpreadsheetDocument document); void visit(PresentationDocument document); }

Classes

package VisitorPatternDemo; class ExportVisitor implements DocumentVisitor { public void visit(TextDocument document) { System.out.println("Exporting Text Document: " + document.getTitle()); // Export text document specific details } public void visit(SpreadsheetDocument document) { System.out.println("Exporting Spreadsheet Document: " + document.getTitle()); // Export spreadsheet document specific details } public void visit(PresentationDocument document) { System.out.println("Exporting Presentation Document: " + document.getTitle()); // Export presentation document specific details } }

Driver

In this example, the DocumentVisitor interface defines the visit methods for each document type (TextDocument, SpreadsheetDocument, and PresentationDocument). The PrintVisitor and ExportVisitor are concrete visitors that implement the DocumentVisitor interface and provide specific implementations of the visit methods.

The Document interface declares the accept method, which accepts a visitor as an argument. Each concrete document class (TextDocument, SpreadsheetDocument, and PresentationDocument) implements the Document interface and defines the accept method, allowing a visitor to visit and perform its specific operation on that document.

In the Main class, an array of documents is created, representing different document types. The PrintVisitor and ExportVisitor are also created. The accept method of each document is called, passing the appropriate visitor. This allows the visitor to visit and perform its operation on each document in the array.

By using the Visitor pattern, new operations or behaviors can be added to the document processing system without modifying the document classes. The visitors encapsulate the specific behaviors or algorithms, and the documents accept the visitors, allowing the behaviors to be applied dynamically. This pattern is particularly useful when dealing with a diverse set of objects with different structures and behaviors, enabling easy extensibility and separation of concerns.