Design Patterns in Action Script-Composite

toad-256x256 Still remember the Interpreter example? No matter what you type is a number or an expression; it can calculate the result just by the clause” new GeneralExpression(inputText.text).interpret()”

clip_image002

clip_image004

It means that we treat the number the same with the expression. Actually, the expression is form by the numbers. So, you can take the expression as a container, it contains the numbers, and the number is a special kind of expression, it calculates itself.

Interpreter

It this picture, you can consider it as a tree. And all the inner nodes are containers, and the leaf node is the Number. We treat all the nodes in the same way, just use the interpret() method. So, the client is very convenient to deal with the expressions. This is what we introduce today, the composite pattern.

The intent of this pattern is as follows.

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

–By GOF BOOK

In the interpreter example, we put the differences of dealing with the inner node and leaf node into the concrete class. And leave a common interface for the client to deal with. This is what the composite pattern does.

This pattern is very useful, especially when you building a user interface. You can treat display object and display container object the same way, without considering the differences between the two objects. It’s very common in the GUI building environment.

Of course, it has its own disadvantages. For example, you need to carefully avoid two or more composites to form a cycle. Remember, be a tree, not a cycle! Download Download Full Project

Enjoy!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • Technorati
  • StumbleUpon
  • Twitter
RSS Enjoy this Post? Subscribe to Ntt.cc

RSS Feed   RSS Feed     Email Feed  Email Feed Follow us Follow us
You can leave a response, or trackback from your own site.

Leave a Reply