Chapter 31. Composite


© Jennifer M. Kohnke

A composite is a euphemism for a lie. It's disorderly. It's dishonest and it's not journalism.

Fred W. Friendly, 1984

The COMPOSITE pattern is a very simple pattern that has significant implications. The fundamental structure of the COMPOSITE pattern is shown in Figure 31-1. Here, we see a hierarchy based on shapes. The Shape base class has two derivative shapes: Circle and Square. The third derivative is the composite. CompositeShape keeps a list of many Shape instances. When called on CompositeShape, Draw() delegates that method to all the Shape instances in the list.

Figure 31-1. COMPOSITE pattern


Thus, an instance of CompositeShape appears to the system to be a single Shape. It can be passed to any function or object that takes a Shape, and it will behave like a Shape. However, it is really a proxy[1] for a group of Shape instances. Listings 31-1 and 31-2 show one possible implementation of CompositeShape.

[1] Note the similarity in structure to the PROXY pattern.

Listing 31-1. Shape.cs

public interface Shape {   void Draw(); }

Listing 31-2. CompositeShape.cs

using System.Collections; public class CompositeShape : Shape {   private ArrayList itsShapes = new ArrayList();   public void Add(Shape s)   {     itsShapes.Add(s);   }   public void Draw()   {     foreach (Shape shape in itsShapes)       shape.Draw();   } }




Agile Principles, Patterns, and Practices in C#
Agile Principles, Patterns, and Practices in C#
ISBN: 0131857258
EAN: 2147483647
Year: 2006
Pages: 272

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net