From "Design Patterns"
🎧 Listen to Summary
Free 10-min PreviewFlexible Document Formatting
Key Insight
Beyond representing document content, Lexi must construct a properly formatted physical structure by arranging basic text and graphics into lines, columns, and pages. This 'formatting' or 'linebreaking' process is intricate, involving numerous constraints and trade-offs between formatting quality, speed, and storage requirements. A primary design objective is to maintain independence between formatting algorithms and the document structure, allowing new glyph subclasses or formatting algorithms to be introduced without requiring modifications to existing components.
The chosen solution encapsulates the formatting algorithm within a dedicated object, facilitating easy changes at compile-time or even run-time. A 'Compositor' class hierarchy is established, where each subclass implements a specific formatting algorithm. A special 'Glyph' subclass named 'Composition' acts as the context, holding the unformatted visible glyphs that form the document's fundamental content. When formatting is necessary, the 'Composition' object directs its assigned 'Compositor' to 'Compose' its children.
The 'Compositor' then iterates through the 'Composition''s children, inserting structural glyphs such as 'Row' and 'Column' according to its specific linebreaking algorithm. For example, a 'SimpleCompositor' might execute a quick pass without advanced considerations, while a 'TeXCompositor' would implement the comprehensive TEX algorithm, factoring in document 'color' (even distribution of text and whitespace) for superior quality, albeit with increased processing time. This separation between document structure and formatting algorithms, enabling dynamic algorithm swapping, is a core principle of the Strategy pattern.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Design Patterns summary with audio narration, key takeaways, and actionable insights from Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides.