Design Mode (7) Composite (Structural)

Source: Internet
Author: User

Design Mode (7) Composite (Structural)

1. Overview

In the data structure, the tree structure is very important. We can apply the tree structure to the design mode.

Example 1: multi-level tree menu.

Example 2: files and folders

2. Problem

We can combine simple objects into complex objects, which can be combined into larger objects. We can define simple objects as classes, and then define some container classes to store these simple objects. Client code must distinguish between simple objects and container objects. In fact, most users think they are the same. Different use of these classes makes the program more complex. Recursion is difficult to use. How can we use recursive combinations so that users do not have to distinguish these classes?

3. Solution


Combination Mode
: Combine objects into a tree structure to represent the "part-whole" hierarchy. Composite makes the use of a single object and a Composite object consistent.

Sometimes it is also called the partial-overall mode, which makes the concept of simple elements and complex elements blurred in the tree structure problem. The customer program can process complex elements like simple elements, this decouples the customer program from the internal structure of complex elements.

The combination mode allows you to optimize the processing of recursive or hierarchical data structures. There are many examples of hierarchical data structures, making the combination mode very useful. A general example of hierarchical data structure is what you encounter every time you use a computer: a file system. The file system consists of directories and files. Content can be installed in each directory. The contents of a directory can be files or directories. In this way, computer file systems are organized in recursive structures. If you want to describe such a data structure, you can use the Composite mode.

4. Classification of combination modes

1) define the method for managing child elements in the Composite class
2) define the method for managing child elements in the Component interface, so that the Leaf class needs to implement these methods empty.

5. Applicability

The Composite mode is applicable in the following situations:

1) You want to represent the part of the object-the overall hierarchy

2) You want the user to ignore the differences between the composite object and a single object. The user will use all objects in the composite structure in a unified manner.

6.
Structure



Typical C
The o m p o s I t e object structure is shown in:


7. Composition of the build Mode

Abstract component role (component): it is the object declaration interface in the combination. When appropriate, it implements the default behavior of interfaces common to all classes. Declare an interface to access and manage Component sub-parts.

This interface can be used to manage all sub-objects. (Optional) define an interface in a recursive structure to access a parent component and implement it as appropriate.

Leaf component role (Leaf): indicates the Leaf node object in the composite tree. The Leaf node does not have any subnodes. And define the behavior of the element object in the combination.
Composite: defines the behavior of components with child parts. Storage Sub-parts. Perform operations related to sub-parts in the Component interface.
Client: The component object is manipulated through the component interface.

8. Results

1) • a basic object defined in the class hierarchy that contains basic objects and composite objects can be combined into more complex composite objects, and this composite object can be combined, this keeps recursion. In customer code, you can use composite objects wherever basic objects are used.
2) • Simplified Customer Code customers can use the combination structure and a single object in a consistent manner. Generally, users do not know (or care about) whether a leaf node is processed or a composite component. This simplifies the customer code, because in the classes that define the combination, you do not need to write some functions that are filled with selection statements.
3) • makes it easier to add new types of components. The newly defined composite or leaf subclass automatically works with the existing structure and customer code, and the customer program does not need to change due to the new component class.
4) • making your design more general and easily adding new components will also lead to some problems, that is, it is difficult to limit components in the combination. Sometimes you want a combination to have only some specific components. When using composite, you must check the runtime instead of depending on the type system to apply these constraints.

9. Implementation

A typical example is a tree menu. Multi-level display, this menu can add unlimited nodes; the exception is file traversal and so on.

<? Php/*** combination mode ** @ author guisu * @ version 1.0 * combination mode: tree menu ** combines objects into a tree structure to represent the "part-whole" hierarchy, make the customer's use of a single object and composite object consistent * // *** abstract component role (component) **/abstract class MenuComponent {public function add ($ component) {} public function remove ($ component) {} public function getName () {} public function getUrl () {} public function displayOperation () {}}/*** Composite **/class MenuComposite extends MenuComponent {Private $ _ items = array (); private $ _ name = null; private $ _ align = ''; public function _ construct ($ name) {$ this-> _ name = $ name;} public function add ($ component) {$ this-> _ items [$ component-> getName ()] = $ component ;} public function remove ($ component) {$ key = array_search ($ component, $ this-> _ items); if ($ key! = False) unset ($ this-> _ items [$ key]);} public function getItems () {return $ this-> _ items;} public function displayOperation () {static $ align = '|'; if ($ this-> getItems () {// substr ($ align, strpos ($ align,); $ align. = '_';} else {$ align. = '';} echo $ this-> _ name," <br/> "; foreach ($ this-> _ items as $ name => $ item) {echo $ align; $ item-> displayOperation () ;}} public function getName () {return $ this-> _ name ;}}/*** tree Leaf component role (Leaf) **/class ItemLeaf extends MenuComponent {private $ _ name = null; private $ _ url = null; // public $ _ align = '----'; public function _ construct ($ name, $ url) {$ this-> _ name = $ name; $ this-> _ url = $ url;} public function displayOperation () {echo '<a href = "', $ this-> _ url, '">', $ this-> _ name, '</a> <br/>';} public function getName () {return $ this-> _ name;} class Client {public static function displayMenu () {$ SubMenu1 = new MenuComposite ("submenu1"); $ subMenu2 = new MenuComposite ("submenu2"); $ subMenu3 = new MenuComposite ("submenu3 "); $ subMenu4 = new MenuComposite ("submenu4"); $ subMenu5 = new MenuComposite ("submenu5");/* $ item1 = new ItemLeaf ("sohu", "www.163.com "); $ item2 = new ItemLeaf ("sina", "www.sina.com"); $ subMenu4 = new MenuComposite ("submenu4"); $ subMenu1-> add ($ subMenu4 ); $ subMenu4-> add ($ item1); $ subMen U4-> add ($ item2); */$ item3 = new ItemLeaf ("baidu", "www.baidu.com"); $ item4 = new ItemLeaf ("google ", "www.google.com"); $ subMenu2-> add ($ item3); $ subMenu2-> add ($ item4); $ allMenu = new MenuComposite ("AllMenu "); $ allMenu-> add ($ subMenu1); $ allMenu-> add ($ subMenu2); $ allMenu-> add ($ subMenu3); $ subMenu3-> add ($ subMenu4 ); $ subMenu4-> add ($ subMenu5); $ allMenu-> displayOperation () ;}// create menuClient: displayMenu ();?>

 

 

10. Combination Mode and other related modes

1) The decorator mode is often used with the composite mode. When decoration and combination are used together, they

There is usually a public parent class. Therefore, decoration must support the Component interfaces with Add, Remove, and GetChild operations.

2) The Flyweight mode allows you to share components, but you can no longer reference their parent components.

3) (iterator mode) Itertor can be used to traverse Composite.

4) (Observer mode) Visitor will be originally distributed in Composite and L e a f Class for operations and behavior localization.

11. Conclusion

The combination mode decouples the internal structure of the customer program and complex elements, so that the customer program can process complex elements like simple elements.

If you want to create a hierarchy and treat all elements in the same way, the combination mode is the best choice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.