The English text of the combination mode is: Compose objects into tree structures to represent part-whole hiearachies. Composite lets clients treat individual objects and compositions of objects uniformly. This means that objects are combined into a tree structure to represent a "partial-whole" hierarchy, which makes the user consistent with the use of individual objects and composite objects.
There are three characters in the combo mode:
Abstract component (component) Role: Defines common methods and properties for participating in a composite object.
Leaf component (leaf) role: The role is a leaf object with no branching under it, i.e. no child nodes.
Digital component (Composite) Role: This role represents a group of branched objects under which a branch is grouped, and its role is to combine branches and leaves into a tree structure and define methods for managing sub-objects.
Composite Pattern class Diagram:
The implementation code corresponding to each class:
Code for Abstract Artifacts:
Package com.zz.composite;/** * Abstract Component Interface * Copyright April 25, 2015 * created by TXXS * All right reserved */public interface com ponent {public void operation ();}
Branch Structure Code:
Package Com.zz.composite;import java.util.arraylist;/** * Definition of tree components * Copyright April 25, 2015 * created by TXXS * All right Rese RVed */public class Composite implements Component {//widget container private arraylist<component> componentlist = new Arraylis T<component> ();//Add widget public void Add (Component Component) {this.componentList.add (Component);} Delete widget public void remove (Component Component) {this.componentList.remove (Component);} Get Child widget Public Arraylist<component>getchild () {return this.getchild ();} @Overridepublic void operation () {//Business logic Code}}
Leaf Structure Code:
Package com.zz.composite;/** * Define leaf components * Copyright April 25, 2015 * created by TXXS * All right reserved */public class leaf im Plements Component {@Overridepublic void operation () {//Salesman logic code}}
Advantages of the combined mode:
1. Simple invocation, the user does not have to care about whether they are dealing with a single object or a composite object.
2, flexibility to increase the node, want to increase the branch or leaf node as long as you need to find the parent node, do not need to increase the object parts and modify the code
The scenario in which the combination pattern fits:
1, describe the object's part and the overall hierarchy structure.
2. When it is necessary to ignore the differences between individual parts and composite components
SOURCE download
Design mode-Combined mode