I need write permission to create the entry file. Here's the structured summary I've prepared:
GoF Composite and Decorator Structural Patterns
This entry covers two structural patterns from the Gang of Four catalog—Composite and Decorator—that both use recursive composition through a common interface but for different purposes. Composite models part-whole hierarchies so clients treat individual objects and collections uniformly. Decorator wraps objects to add responsibilities dynamically without subclassing.
---
Key Concepts
Composite Pattern
Intent: Compose objects into tree structures to represent part-whole hierarchies; let clients treat individual objects and compositions uniformly.
Core abstraction: An abstract Component class that represents both primitives (Leaf) and containers (Composite), declaring operations common to both.
Recursive composition: A Composite holds a collection of Components, each of which may itself be a Composite, enabling arbitrarily deep nesting.
Uniform client interface: Clients interact only through the Component interface—they never need to know whether they hold a Leaf or a Composite.
Transparency vs. safety trade-off: Declaring child-management operations (Add/Remove) in Component gives transparency (uniform interface) but sacrifices safety (meaningless operations on leaves). Declaring them only in Composite gives compile-time safety but requires type-testing.
Consequences: Simplifies client code by eliminating type-checking conditionals; makes adding new component types easy; but can make designs overly general since you cannot rely on the type system to restrict which components a composite may contain.
Decorator Pattern
Intent: Attach additional responsibilities to an object dynamically. A flexible alternative to subclassing for extending functionality.
Also known as: Wrapper.
Core mechanism: A Decorator holds a reference to a Component, conforms to the same interface, and forwards requests—optionally performing additional work before or after.
Recursive nesting: Decorators can be nested arbitrarily (e.g., BorderDecorator wrapping ScrollDecorator wrapping TextView), each adding one responsibility.
Run-time flexibility: Responsibilities can be added and removed at run-time by attaching/detaching decorators, unlike inheritance which is static.
Consequences: More flexible than static inheritance; avoids feature-laden base classes; but produces many small objects that can be hard to debug, and breaks object identity (a decorated component is not == to the original).
Commands and Syntax
Composite — GetComposite for safe downcasting (C++)
virtual Composite* GetComposite() { return 0; } // Component default
virtual Composite* GetComposite() { return this; } // Composite override
if (test = aComponent->GetComposite()) {
test->Add(new Leaf); // safe — only executes on actual composites
}