The Composite Design Pattern

You use the composite design pattern when you have items, and also groups of items, and you want to use them in the same way.

For example (and this is a very simplified example!), you have a MenuItem (a single item on a navigation menu), and a MenuItemGroup (a collection of child MenuItem objects. You would make an interface (MenuInterface, with methods such as AllLinks) and both MenuItem and MenuItemGroup would implement this interface.

In the example above, you could have an object (that you know implements MenuInterface, which has a render()) and you can do something simple such as this:

<?php
$items = [ 
new MenuItem("home"),
new MenuItemGroup(['about us','services','contact us']),
new MenuItem("login"),
];

foreach($items as $item) {
  echo "<li>" . $item->render() . "</li>\n";
}

For single menu items, obviously it would output a single, normal link. But render() on the Menu Item Group would have some logic in it to wrap it's child Menu Items (or maybe it even contains more Menu Item Groups!) in some form of a dropdown menu.

The advantages of using the composite design pattern is that your code (such as the foreach loop above) doesn't have to check what type an object is, as it knows it implements the interface and you can call the same methods on single items or groups of items and it will work as expected.

Design pattern type: Structural design pattern

Comments The Composite Design Pattern