Java Design Pattern cainiao series (12) combination pattern modeling and implementation
Composite: the Composite mode is sometimes called partial-overall mode. It combines objects into a tree structure to represent the "partial-whole" hierarchy. The combination mode is convenient for handling tree structure problems.
I. uml modeling:
Ii. Code Implementation
/*** Example: the combination mode is also called "Integration-Partial" Mode **. The combination mode is more convenient for ** node */class TreeNode {/** node name */private when dealing with tree structure problems. string name; private TreeNode parent; private ArrayList
Children = new ArrayList
(); Public TreeNode (String name) {this. name = name;}/*** encapsulate related attributes */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;}/*** add, delete, and query a child node */public void add (TreeNode node) {children. add (node);} public void delete (TreeNode node) {children. add (node);} public Iterator
GetChildren () {return children. iterator () ;}}/*** client Test class ** @ author Leo */public class Test {public static void main (String [] args) {TreeNode rootNode = new TreeNode (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
Iterator = rootNode. getChildren (); while (iterator. hasNext () {System. out. println (iterator. next (). getName ());}}}
DescriptionThe following tree is constructed:
Iii. application scenarios
Multiple objects are combined for operation. It is often used to represent a tree structure, such as a binary tree.
Iv. Summary
The combination allows the customer to process individual objects and object combinations in a consistent manner.