Design pattern (vii) Combination mode composite (structural type)

Source: Internet
Author: User
Tags vars

Design pattern (vii) Combination mode composite (structural type)

1. Overview

In the data structure, the tree structure is very important, we can apply the structure of the tree to the design pattern inside.

Example 1: A multi-level tree menu.

Example 2: Files and folders directory

2. Questions

We can combine complex objects with simple objects, and this complex object can be combined into larger objects. We can define simple objects as classes and then define some container classes to store these simple objects. The client code must distinguish between object simple objects and container objects, but in most cases the user thinks they are the same. The difference between these classes makes the program more complex. Recursion is used with trouble, and how do we use recursive combinations so that users don't have to differentiate between these classes?

3. Solution

composition Mode : Combines objects into a tree structure to represent a "partial-whole" hierarchy. Composite makes the user consistent with the use of individual objects and composite objects.

Sometimes called part-overall mode, it blurs the concept of simple elements and complex elements in the problem of our tree structure, and the client program can deal with complex elements like simple elements, thus decoupling the client program from the internal structure of the complex elements.

The combined mode allows you to optimize the processing of recursive or hierarchical data structures. There are many examples of hierarchical data structures that make combinatorial patterns very useful. A universal example of hierarchical data structures is what you encounter every time you use a computer: the file system. The file system consists of directories and files. Each directory can be loaded with content. The contents of a directory can be either a file or a directory. In this way, the computer's file system is organized in a recursive structure. If you want to describe such a data structure, then you can use the combined mode composite.

4. Classification of combinatorial patterns

1) Define the methods for managing child elements in the composite class
2) Define the methods for managing child elements in the component interface so that the leaf class needs to implement NULL for these methods.

5. Applicability

The composite mode is applicable in the following cases:

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

2). You want users to ignore the difference between a combined object and a single object, and the user will use all the objects in the composite structure uniformly.

6. Structure



The typical c o m P o s i t e object structure is shown in the following:


7. Composition of the build pattern

Abstract component Role (component): Is an object declaration interface in a composition that implements the default behavior of all classes in common with appropriate conditions. Declares an interface for accessing and managing component subassemblies.

This interface can be used to manage all child objects. Optionally, define an interface in the recursive structure to access a parent part and implement it where appropriate.

Leaf component Role (leaf): The leaf node object is represented in the composition tree, and the leaf node has no child nodes. and defines the behavior of the entity objects in the composition.
Branch component Role (Composite): Defines the behavior of those parts that have child parts. Stores the child parts. Implement operations related to subassemblies in the component interface.
Customer role (client): The object that manipulates the combined part through the component interface.

8. Effects

1) • Defines a class hierarchy containing basic objects and composite objects The basic objects can be combined into more complex objects, and this combination of objects can be combined so that they continue recursively. In the customer code, you can use a composite object wherever you use the base object.
2) • Simplify customer code customers can consistently use composite structures and individual objects. Usually the user does not know (and does not care) whether the processing is a leaf node or a composite component. This simplifies the customer code, because there is no need to write some functions that are riddled with selection statements in those classes that define the composition.
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 client program does not need to be changed by the new component class.
4) • Make your design more generalized it is also problematic to add new components, which makes it difficult to limit the components in a composition. Sometimes you want a combination to have only some specific components. When using composite, you cannot rely on the type system to impose these constraints, but must be checked at run time.

9. Implement

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

[PHP]View Plain Copy print?
  1. <?php
  2. /**
  3. * Combination Mode
  4. *
  5. * @author Guisu
  6. * @version 1.0
  7. * Combo Mode: Tree Menu
  8. *
  9. * Combine objects into a tree structure to represent a "partial-whole" hierarchy that enables customers to have consistent use of individual objects and composite objects
  10. */
  11. /**
  12. * Abstract Component Roles (component)
  13. *
  14. */
  15. Abstract class MenuComponent
  16. {
  17. Public function Add ($component) {}
  18. Public function Remove ($component) {}
  19. Public function GetName () {}
  20. Public function GetUrl () {}
  21. Public function Displayoperation () {}
  22. }
  23. /**
  24. * Branch Component Role (Composite)
  25. *
  26. */
  27. Class Menucomposite extends MenuComponent
  28. {
  29. private $_items = Array ();
  30. private $_name = null;
  31. private $_align = ';
  32. Public function __construct ($name) {
  33. $this->_name = $name;
  34. }
  35. Public function Add ($component) {
  36. $this->_items[$component->getname ()] = $component;
  37. }
  38. Public function Remove ($component) {
  39. $key = array_search ($component,$this->_items);
  40. if ($key!== false) unset ($this->_items[$key]);
  41. }
  42. Public function GetItems () {
  43. return $this->_items;
  44. }
  45. Public function displayoperation () {
  46. static $align = ' | ';
  47. if ($this->getitems ()) {
  48. //substr ($align, Strpos ($align,));
  49. $align. = ' _ _ ';
  50. }else{
  51. $align. =';
  52. }
  53. echo $this->_name, "<br/>";
  54. foreach ($this->_items as $name = + $item) {
  55. echo $align;
  56. $item->displayoperation ();
  57. }
  58. }
  59. Public function GetName () {
  60. return $this->_name;
  61. }
  62. }
  63. /**
  64. * Leaf component Role (leaf)
  65. *
  66. */
  67. Class Itemleaf extends MenuComponent
  68. {
  69. private $_name = null;
  70. private $_url = null;
  71. //public $_align = '----';
  72. Public function __construct ($name,$url)
  73. {
  74. $this->_name = $name;
  75. $this->_url = $url;
  76. }
  77. Public function displayoperation ()
  78. {
  79. echo ' <a href= ', $this->_url, ' > ', $this->_name, ' </a><br/> ';
  80. }
  81. Public function GetName () {
  82. return $this->_name;
  83. }
  84. }
  85. Class Client
  86. {
  87. public static function DisplayMenu ()
  88. {
  89. $subMenu 1 = new Menucomposite ("submenu1");
  90. $subMenu 2 = new Menucomposite ("submenu2");
  91. $subMenu 3 = new Menucomposite ("Submenu3");
  92. $subMenu 4 = new Menucomposite ("Submenu4");
  93. $subMenu 5 = new Menucomposite ("Submenu5");
  94. /* 
  95. $item 1 = new Itemleaf ("Sohu", "www.163.com");
  96. $item 2 = new Itemleaf ("Sina", "www.sina.com");
  97. $subMenu 4 = new Menucomposite ("Submenu4");
  98. $subMenu 1->add ($subMenu 4);
  99. $subMenu 4->add ($item 1);
  100. $subMenu 4->add ($item 2);
  101. */
  102. $item 3 = new Itemleaf ("Baidu","www.baidu.com");
  103. $item 4 = new Itemleaf ("Google","www.google.com");
  104. $subMenu 2->add ($item 3);
  105. $subMenu 2->add ($item 4);
  106. $allMenu = new Menucomposite ("Allmenu");
  107. $allMenu->add ($subMenu 1);
  108. $allMenu->add ($subMenu 2);
  109. $allMenu->add ($subMenu 3);
  110. $subMenu 3->add ($subMenu 4);
  111. $subMenu 4->add ($subMenu 5);
  112. $allMenu->displayoperation ();
  113. }
  114. }
  115. Create a Menu
  116. Client::d isplaymenu ();
  117. ?>


10. Combination mode and other related modes

1) Decorative mode (decorator mode) is often used in conjunction with Composite mode. When used together with decorations and combinations, they

There is usually a common parent class. The adornment must therefore support the component interface with ADD, remove, and getchild operations.

2) Flyweight mode lets you share components, but no longer refer to their parent parts.

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

4) (Observer mode) visitor the operations and behavior localization that should have been distributed in the composite and L e a F classes.

11. Summary

The combined mode decouples the internal structure of the client and complex elements, allowing the client program to handle complex elements as simple elements.

If you want to create hierarchies and can treat all the elements in the same way, then the combined pattern is the ideal choice.

Design pattern (vii) Combination mode composite (structural type)

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.