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.
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 allDesign 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.
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.