Chapter 3. Structural Patterns: Composite and Flyweight
The Composite and Flyweight structural patterns apply to systems that have many data objects. The Composite pattern has wide applicability, and its composite lists can also make use of the Flyweight pattern. The Flyweight pattern shares identical objects behind the scenes to save space. In their implementations, these patterns make use of the following novel C# features:
Generics
Properties
Structs
Indexers
Implicit typing
Initializers
Anonymous types
Composite Pattern
Role
The Composite pattern arranges structured hierarchies so that single components and groups of components can be treated in the same way. Typical operations on the components include add, remove, display, find, and group.
Illustration
Computer applications that specialize in grouping data abound these days. Consider a music playlist in iTunes or a digital photo album in Flickr or iPhoto (Figure 3-1). Items are put in a large list, which is then given structure separately.
Figure 3-1. Composite pattern illustration—iPhoto
Looking at the screenshot from iPhoto, we can see that there are different ways of viewing the photos that have been imported: chronologically or by named event. A single photo can appear in many albums ("Last Roll," "2007," and "Switzerland," for example). Creating an album forms a composite object but does not entail actually copying the photos. In this ...
Get C# 3.0 Design Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.