Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4 Structural Patterns > Composite Pattern

Composite Pattern

What Is a Composite Pattern?

The Composite pattern is a collection pattern that allows you to compound different subsets of functionality into a collection and then call each subset in turn in the collection at a given point.

Let’s say you had a collection of objects, and each object had a particular method that you wanted to call in series. You could call each method in the collection separately, but this would take time and a lot of code:


obj1.Operation();
obj2.Operation();
obj3.Operation();
obj4.Operation();
obj5.Operation();
obj6.Operation();
obj7.Operation();
...... and so on

Instead, a composite allows you to call the classes with a single method and loop through the collection, calling the method on each class. This remains flexible because each class in the collection as well as the collection class itself all derive from the same base class. We differentiate between them by their function.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint