Merging mode: Composite (converted from a. Net)

Source: Internet
Author: User
Composite Mode

The merging mode is sometimes called part-whole ). The merging mode organizes objects into the tree structure and can be used to describe the relationship between the whole and the part. The merging mode allows the client to view elements as compound elements.

Talking about Monk stories

This is what my grandmother told me when I was a child: I used to have a mountain, a temple in the mountains, and an old monk in the temple is telling a story to the little monk. What is the story? Once upon a time there was a mountain, and there was a temple in the mountains ....... How many times will Grandma's story be circulated, depending on how long you will fall asleep. There are mountains, temples, monks, and stories in the story. Therefore, there are two types of Role in the story: one has no other roles, and the other has other roles.

Object Tree Structure

A tree structure consists of two types of nodes: tree branches and leaf nodes. Tree branches can have subnodes, but a leaf node cannot have subnodes. Except the root node, other nodes have only one parent node.

Note: A tree branch node does not contain any leaves, but it is still a tree branch node because it has the ability to carry leaves, instead of a leaf node. A leaf node can never contain child nodes.

Ii. Overview of merging Modes

The class diagram is omitted from the details of each role.

It can be seen that the above class graph structure involves three roles:

Abstract component role: This is an abstract role that specifies an interface for the objects involved in the combination. This role provides a common interface and its default behavior.
Leaf component (leaf) Role: represents the leaf object that participates in the combination. A leaf object has no sub-objects.
Composite role: represents the object with sub-objects in the combination, and shows the behavior of the object.
It can be seen that composite objects can contain other component objects. In other words, a composite object can contain other composite or leaf objects.

The implementation of the merging mode is divided into two forms based on the differences between the Implemented interfaces, namely the security mode and the transparent mode. The merging mode does not provide a parent object management method, but the merging mode must provide sub-object management methods (such as add, remove, and getchild) where appropriate ).

Transparent Mode

As the first option, declare all methods in component to manage subclass objects, including add (), remove (), and getchild () methods. The advantage of this is that all component classes have the same interfaces. In the client's view, the difference between a leaf object and a synthetic object disappears at the interface level, and the client can treat all objects at the same level. This is the synthesis mode in transparent form.

The disadvantage of this choice is that it is not safe, because leaf objects and synthetic objects are essentially different. Leaf objects cannot have objects of the next level. Therefore, the add (), remove (), and getchild () methods have no meaning. They do not make errors during compilation, errors only occur during running.

Security Mode

The second option is to declare all methods in the composite class to manage subclass objects. This approach is safe because leaf objects do not have any method to manage subclass objects. Therefore, if the client uses these methods for leaf objects,ProgramErrors occur during compilation.

The disadvantage of this choice is that it is not transparent, because the leaf class and the synthesis class will have different interfaces.

These two forms have their own advantages and disadvantages and need to be decided based on the specific circumstances of the software.

Iii. Structure of safe synthesis Mode

The safe synthesis mode requires that the management clustering method only appears in the tree component class, but not in the leaf component.


This form involves three roles:

Abstract component role: This is an abstract role that defines public interfaces and default actions for the objects involved in the combination and can be used to manage all sub-objects. In a safe synthesis mode, the component role does not define a method for managing sub-objects. This definition is provided by the Branch component object.
Leaf component (leaf) Role: A leaf object is an object without sub-child objects and defines the behavior of the original objects in the combination.
Composite role: indicates the object with sub-object in the combination. The branches object provides all methods for managing sub-objects, such as add (), remove (), and getchild.

Iv. Safe synthesis mode implementation

The following examplesCodeDemonstrates the safe synthesis mode code:

 

 // Composite pattern -- Structural example  Using System;Using System. text; Using System. collections; // "Component"  Abstract   Class Component { // Fields    Protected   String Name; // Constructors    Public Component ( String Name ){ This . Name = Name ;} // Operation    Public   Abstract   Void Display ( Int Depth );} // "Composite"  Class Composite: component { // Fields    Private Arraylist children = New Arraylist (); // Constructors    Public Composite ( String Name ): Base (Name ){} // Methods    Public   Void Add (Component component) {children. Add (component );} Public   Void Remove (Component component) {children. Remove (component );} Public   Override   Void Display ( Int Depth) {console. writeline ( New String ( '-' , Depth) + name ); // Display each of the node's children      Foreach (Component component In Children) component. Display (depth + 2 );}} // "Leaf"  Class Leaf: component { // Constructors    Public Leaf ( String Name ): Base (Name ){} // Methods    Public   Override   Void Display ( Int Depth) {console. writeline ( New String ( '-' , Depth) + name );}} /**/ /// <Summary> /// Client Test  /// </Summary>  Public   Class Client { Public   Static   Void Main ( String [] ARGs ){ // Create a Tree Structure Composite root = New Composite ( "Root" ); Root. Add ( New Leaf ( "Leaf" ); Root. Add (New Leaf ( "Leaf B" ); Composite comp = New Composite ( "Composite X" ); Comp. Add ( New Leaf ( "Leaf xa" ); Comp. Add ( New Leaf ( "Leaf XB" ); Root. Add (COMP); root. Add ( New Leaf ( "Leaf C" )); // Add and remove a leaf Leaf L = New Leaf ( "Leaf D" ); Root. Add (l); root. Remove (L ); // Recursively display nodes Root. Display (1 );}}

V. Transparent synthesis mode structure

Different from the safe synthesis mode, the transparent synthesis mode requires that all specific component classes, regardless of the branches or leaves, comply with a fixed interface.


This form involves three roles:

Abstract component role: This is an abstract role that specifies an interface for the objects to be combined to standardize common interfaces and default behaviors.
Leaf component (leaf) Role: this role represents the leaf objects that participate in the combination and defines the behavior of the original objects that participate in the combination. The leaf class provides mediocre implementation of methods used to manage sub-classes on objects, such as add (), remove (), and getchild.
Composite role: represents the object with sub-objects in the combination and defines the behavior of such objects.

Vi. Transparent synthesis mode implementation

The following sample code demonstrates the safe merging mode code:

 // Composite pattern -- Structural example  Using System; Using System. text; Using System. collections; // "Component"  Abstract   Class Component { // Fields    Protected   String Name; // Constructors    Public Component ( String Name ){ This . Name = Name ;} // Methods    Abstract   Public   Void Add (component C ); Abstract   Public   Void Remove (component C ); Abstract   Public  Void Display ( Int Depth );} // "Composite"  Class Composite: component { // Fields    Private Arraylist children = New Arraylist (); // Constructors    Public Composite ( String Name ): Base (Name ){} // Methods    Public   Override   Void Add (Component component) {children. Add (component );} Public   Override   Void Remove (Component component) {children. Remove (component );} Public   Override   Void Display ( Int Depth) {console. writeline ( New String ( '-' , Depth) + name ); // Display each of the node's children      Foreach (Component component In Children) component. Display (depth + 2 );}} // "Leaf"  Class Leaf: component { // Constructors    Public Leaf ( String Name ): Base (Name ){} // Methods    Public   Override   Void Add (component C) {console. writeline ( "Cannot add to a leaf" );} Public   Override   Void Remove (component C) {console. writeline ( "Cannot remove from a leaf" );} Public   Override   Void Display ( Int Depth) {console. writeline ( New String ( '-' , Depth) + name );}} /**/ /// <Summary>/// Client Test  /// </Summary>  Public   Class Client { Public   Static   Void Main ( String [] ARGs ){ // Create a Tree Structure Composite root = New Composite ( "Root" ); Root. Add ( New Leaf ( "Leaf" ); Root. Add ( New Leaf ( "Leaf B" ); Composite comp = New Composite ( "Composite X" ); Comp. Add ( New Leaf ( "Leaf xa" ); Comp. Add ( New Leaf ( "Leaf XB" ); Root. Add (COMP); root. Add ( New Leaf ( "Leaf C" )); // Add and remove a leaf Leaf L = New Leaf ( "Leaf D" ); Root. Add (l); root. Remove (L ); // Recursively display nodes Root. Display (1 );}}

7. Several considerations when using the merging mode

Obviously, the reference of the parent object is given. The parent object reference is provided in the sub-object, which can easily traverse all parent objects. With this reference, you can easily apply the responsibility chain mode.
In a general system, you can share components using the metadata mode. However, because the objects in the merging mode often have references to the parent object, sharing is not easy to implement.
Sometimes the system needs to traverse the child component of a tree branch structure for many times. At this time, you can consider storing the result of traversing the child component in the parent component as a cache.
Regarding the data type used to store sub-objects, arraylist is used in schematic code, and other clustering or arrays can be used in the actual system.
The client tries its best not to directly call methods in the leaf class, but to use the polymorphism of its parent class (Component) to complete the call, which can increase code reusability.

8. Monk stories

IX. An example of practical application of the composite mode

The following is an application that demonstrates some basic image elements (such as straight lines and gardens) and some composite image elements (composed of basic image elements) the process of building a complex Graphic Tree.

 // Composite pattern -- real world example  Using System; Using System. collections; // "Component"  Abstract   Class Drawingelement { // Fields    Protected   String Name; // Constructors    Public Drawingelement ( String Name ){ This . Name = Name ;} // Operation    Abstract   Public   Void Display ( Int Indent );} // "Leaf"  Class Primitiveelement: drawingelement { // Constructors   Public Primitiveelement ( String Name ): Base (Name ){} // Operation    Public   Override   Void Display ( Int Indent) {console. writeline ( New String ( '-' , Indent) + "Draw a {0 }" , Name );}} // "Composite"  Class Compositeelement: drawingelement { // Fields    Private Arraylist elements = New Arraylist ();// Constructors    Public Compositeelement ( String Name ): Base (Name ){} // Methods    Public   Void Add (drawingelement d) {elements. Add (d );} Public   Void Remove (drawingelement d) {elements. Remove (d );} Public   Override   Void Display ( Int Indent) {console. writeline ( New String ( '-' , Indent) + "+" + Name );// Display each child element on this node      Foreach (Drawingelement C In Elements) C. Display (indent + 2 );}} /**/ /// <Summary> /// Compositeapp Test  /// </Summary>  Public   Class Compositeapp { Public   Static   Void Main ( String [] ARGs ){ // Create a Tree Structure Compositeelement root = New Compositeelement ( "Picture" ); Root. Add ( New Primitiveelement ( "Red Line" ); Root. Add ( New Primitiveelement ( "Blue Circle" ); Root. Add ( New Primitiveelement ( "Green Box" ); Compositeelement comp = New Compositeelement ( "Two Circles" ); Comp. Add ( New Primitiveelement ( "Black Circle" ); Comp. Add ( New Primitiveelement ( "White Circle" ); Root. Add (COMP ); // Add and remove a primitiveelement Primitiveelement L =New Primitiveelement ( "Yellow Line" ); Root. Add (l); root. Remove (L ); // Recursively display nodes Root. Display (1 );}}

The merging mode is related to many other modes and will be introduced later.

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.