O'Reilly logo

C# 3.0 Design Patterns by Judith Bishop

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Composite pattern illustration—iPhoto

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required