Without knowing it you are already familiar with the composite design pattern.
The file system on all PCs is actually the composite pattern at work. The composite pattern is also present in certain types of structured data, like XML files.
Outside the realm of software development the composite pattern is also present. Think of a physical shop with categories and products or your own family tree, containing children, parents and siblings.
Have you figured out what the composite design pattern is?
The composite pattern is a tree structure containing information. The information is represented in tree branches and tree leafs, just like a regular tree. Both branches and leafs are referred to as nodes (diagram 1):
The composite pattern implements two basic but essential rules:
1. A tree branch can contain an infinite number of other tree branches and tree leafs (acting as folders in a file system).
2. A tree leaf cannot contain other tree branches or tree leafs, therefore acting as endpoints in the tree.
The composite pattern is capable of organizing unstructured data into a structured tree, treating all data elements as uniform objects. The last part is a key concept for the composite pattern.
Unlike XML, which is also a structured tree, XML consists of several objects like XML Document, XML Lists and XML Nodes. When building your ActionScript 3.0 application you simply refer to data as nodes, no matter how data is structured on the sublevel.
When building ActionScript 3 applications you can structure menus, page, subpages, products and categories with the composite pattern. One way of using the composite pattern is to read your XML file and convert it into a composite tree passing a composite node to each new page in your web application. The composite tree is simple yet powerful.
With the composite tree you can easily access other nodes, since all nodes have relative references to each other. By using methods like parent(), firstChild() and children() you can move up, down, left and right in the tree, making information easy accessible.
Take a look a diagram 3 and the sibling relationship. Just like children and parents you can easily access nodes on the same level in the structure by asking for siblings. On any given node in the tree you can use the methods nextSibling(), previousSibling(), firstSibling(), lastSibling(), numSiblings() and siblings(), where the last method would return all the siblings on that level contained in a collection (like an Array, Vector or your own datatype).
Leave a Reply
You must be logged in to post a comment.