Reprint Please specify source: http://blog.csdn.net/lhy_ycu/article/details/39828653
Combined Mode (Composite): The combined mode is sometimes called part-whole mode, which combines objects into a tree structure to represent the "partial-whole" hierarchy. The combination mode is convenient when dealing with the problem of tree structure.
First, UML modeling:
Second, the Code implementation
/** * Example: Combination mode is sometimes called "consolidation-Partial" mode * * Combined mode is convenient when dealing with tree structure problems * Node */class TreeNode {/** node name */private String name;private TreeN Ode parent;private arraylist<treenode> children = new arraylist<treenode> ();p ublic TreeNode (String name) { THIS.name = name;} /** * Encapsulation of related properties */public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public TreeNode getParent () {return parent;} public void SetParent (TreeNode parent) {this.parent = parent;} /** * Additions and deletions to child nodes */public void Add (TreeNode node) {children.add (node);} public void Delete (TreeNode node) {children.add (node);} Public iterator<treenode> GetChildren () {return children.iterator ();}} /** * Client Test class * * @author Leo */public class Test {public static void main (string[] args) {TreeNode RootNode = new Treenod E ("A"); TreeNode BNode = new TreeNode ("B"); TreeNode CNode = new TreeNode ("C"); TreeNode Dnode = new TreeNode ("D"); Rootnode.add (BNode); Rootnode.add (CNode); Cnode.add (Dnode); Iterator<treenode > Iterator= Rootnode.getchildren (); while (Iterator.hasnext ()) {System.out.println (Iterator.next (). GetName ());}}}
Description, which constructs a tree like this:
Third, the application scenario
Multiple objects are grouped together and are often used to represent tree structures, such as binary trees.
Iv. Summary
The combination enables the customer to handle individual objects and object combinations in a consistent manner.
Java Design Patterns Rookie series (12) modeling and implementation of combinatorial patterns