From "Design Patterns"
🎧 Listen to Summary
Free 10-min PreviewDynamic User Interface Embellishment
Key Insight
To enhance Lexi's user interface with features like scroll bars and borders, a flexible mechanism is required for easy, run-time addition and removal of these embellishments without coupling them tightly to other UI objects. Employing inheritance for such extensions typically leads to a 'class explosion,' where a new class is needed for every combination of embellishments (e.g., 'Bordered-ScrollableComposition'), rendering the design unmanageable as the variety of embellishments grows.
The design implements 'transparent enclosure' through object composition, where embellishments are themselves 'Glyph' subclasses (e.g., 'Border', 'Scroller') that contain and delegate operations to the glyph they embellish. An abstract 'MonoGlyph' class serves as the base for these embellishment glyphs; it stores a reference to a component glyph and, by default, forwards all requests to it. This design ensures clients interact uniformly with embellished or unembellished glyphs, maintaining transparency.
'MonoGlyph' subclasses reimplement specific forwarding operations to extend or modify behavior. For instance, 'Border::Draw' first invokes 'MonoGlyph::Draw' on its component to render the underlying content, then draws the border. Similarly, 'Scroller' draws its component within clipped bounds determined by scroll bar positions. This allows for flexible layering, such as a 'Border' enclosing a 'Scroller' which in turn encloses the 'Composition' instance, facilitating experimentation with embellishment order and freeing clients from embellishment-specific code. This approach, adding responsibilities to objects dynamically, is known as the Decorator 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.