Example: Photo Library

In this example, we are concerned with collecting the filenames of digital photos into named sets. We will not use actual images in this example, just filenames as strings. The client is given a domain-specific set of commands with which to create and manipulate the library. Central to the manipulation of the library, from the user's point of view, is "where we are." We start out at an empty set called "Album." Some of the commands leave the system at the component that has just been adjusted, whereas others move it back to the first component in the set. The commands are:

AddSet

Add a new empty set with a name and stay there.

AddPhoto

Add a new named photo after the pointer and stay there.

Find

Find the named component (set or photo), or return null if it is not found.

Remove

Remove the named component (set or photo) and stay at the set from which it was removed.

Display

Display the whole structure.

Quit

Exit the program.

Thus, the two operations that work on either Components or Composites are Find and Remove. Consider some examples of the workings of this system, illustrated in Example 3-2. The input commands are shown in the middle, the result of Display is shown on the left, and some commentary appears on the right.

Tip

The input file contains all the commands in the middle. The program will expect this file to be called Composite.dat.

Example 3-2. Composite pattern—Photo Library sample run

 AddSet Home AddPhoto Dinner.jpg AddSet Pets Going down another level AddPhoto ...

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.