Composite Design Pattern

Composite is a structural design pattern that allows you to compose objects into tree structures and then work with these structures as if they were individual objects.

The application needs to manipulate a hierarchical collection of “primitive” and “compound” objects. Processing of a primitive object is handled in one way and processing of a composite object is handled differently. You don’t want to have to query the “type” of each object before trying to process it.

Define an abstract base class (Component) that specifies the behavior to be exerted uniformly on all primitive and composite objects. Subclass the Primitive and Composite classes outside of the Component class. Each composite object “docks” itself only with the abstract type component, since it manages its “children”.

Use this pattern whenever you have “compounds that contain components, each of which could be a compound.”

Let’s look at the example I wrote as below.

PHP Code Sample

C# Code Sample

By Yuuma.




tel. 06-6454-8833(平日 10:00~17:00)