Behavioral PatternsTemplate Method PatternMedium⏱️ ~2 min

Applying Template Method: Document Processing System

Let's design a document processing system where different document types (PDF, Word, XML) follow the same processing workflow but have type-specific parsing and validation logic. This demonstrates how Template Method eliminates duplication while maintaining flexibility.

DocumentProcessor
- filePath: String
+ processDocument(): void
# parseContent(): Content
# validateStructure(): boolean
# extractMetadata(): Metadata
# beforeProcessing(): void
- saveToDatabase(data): void
PdfProcessor
# parseContent()
# validateStructure()
# extractMetadata()
WordProcessor
# parseContent()
# validateStructure()
# extractMetadata()
# beforeProcessing()
XmlProcessor
# parseContent()
# validateStructure()
# extractMetadata()
Template Method Implementation:
processDocument():
  beforeProcessing()        // hook: empty by default
  content = parseContent()  // abstract: varies by type
  if not validateStructure() then
    throw ValidationError
  end
  metadata = extractMetadata()  // abstract: varies by type
  saveToDatabase(content, metadata)  // concrete: same for all
  logSuccess()              // concrete: same for all

Design Decisions:

First, Template Method (processDocument()): Marked as final to ensure all documents follow the same workflow: preprocessing, parsing, validation, metadata extraction, and persistence. Clients call this method without worrying about implementation details.

Second, Abstract Operations: parseContent(), validateStructure(), and extractMetadata() are abstract because each document format has unique parsing logic. PDF uses binary parsing, Word uses XML-based OOXML parsing, and XML uses DOM parsing.

Third, Hook Method (beforeProcessing()): Provides an optional extension point. WordProcessor overrides this to decrypt password-protected documents, but PdfProcessor and XmlProcessor use the default empty implementation.

Fourth, Concrete Methods: saveToDatabase() and logSuccess() are concrete because all processors store data identically regardless of format.

Interview Tip: When designing template methods, identify invariant steps (same for all subclasses) versus variant steps (differ per subclass). Only variant steps should be abstract or hooks.

Exception Handling: If validateStructure() fails, the template method throws an exception and halts processing. This prevents invalid data from reaching the database. If you need different error handling per document type, make handleValidationError() an abstract method instead of throwing in the template.

💡 Key Takeaways
Template method defines document processing workflow
Abstract methods handle format-specific parsing and validation
Hook methods enable optional preprocessing without forcing all subclasses to implement
Concrete methods handle common operations like database persistence
Validation occurs within template method to ensure consistent error handling
📌 Examples
1PdfProcessor parses binary streams and validates PDF structure
2WordProcessor decrypts protected documents via beforeProcessing() hook
3XmlProcessor validates against XSD schemas
← Back to Template Method Pattern Overview