Design Patterns in Action Script-Composite

xiaoxiao2021-03-01  13

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()”

 

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.

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 Full Project

Enjoy!

相关资源:带音效新年烟花动画特效-HTML-代码
转载请注明原文地址: https://www.6miu.com/read-4050030.html

最新回复(0)