from abc import ABC, abstractmethod
class Document(ABC):
@abstractmethod
def accept(self, visitor):
pass
class PDFDocument(Document):
def accept(self, visitor):
visitor.visit_pdf_document(self)
def get_pdf_text(self):
return "This is a PDF document text."
class WordDocument(Document):
def accept(self, visitor):
visitor.visit_word_document(self)
def get_word_text(self):
return "This is a Word document text."
class Visitor(ABC):
@abstractmethod
def visit_pdf_document(self, document: PDFDocument):
pass
@abstractmethod
def visit_word_document(self, document: WordDocument):
pass
class PrintVisitor(Visitor):
def visit_pdf_document(self, document: PDFDocument):
print("Printing PDF:", document.get_pdf_text())
def visit_word_document(self, document: WordDocument):
print("Printing Word Document:", document.get_word_text())
class ExportVisitor(Visitor):
def visit_pdf_document(self, document: PDFDocument):
print("Exporting PDF to text:", document.get_pdf_text())
def visit_word_document(self, document: WordDocument):
print("Exporting Word Document to text:", document.get_word_text())
# Создаем документы
pdf = PDFDocument()
word = WordDocument()
# Создаем посетителей
print_visitor = PrintVisitor()
export_visitor = ExportVisitor()
# Выполняем операции через посетителей
pdf.accept(print_visitor) # Printing PDF: This is a PDF document text.
pdf.accept(export_visitor) # Exporting PDF to text: This is a PDF document text.
word.accept(print_visitor) # Printing Word Document: This is a Word document text.
word.accept(export_visitor) # Exporting Word Document to text: This is a Word document text.