composition Mode : Combines objects into a tree structure to represent a "partial-overall" hierarchy.
The combined mode makes the user consistent with the use of individual objects and composite objects.
application : When a requirement is a structure that reflects part and overall hierarchy, and if you want users to be able to ignore the difference between a combined object and a single object, you should consider combining patterns when you use all the objects in a composite structure uniformly.
First define a componet abstract class
public abstract class Component {protected String name; public component (String name) {this . Name=name; } //abstract method public Abstract void add (Component c); public abstract void delete (Component c); public abstract void dispaly (int depth);}
Define leaf Node object leaf, inherit componet
Public class Leaf extends Component { Public Leaf(String name) {Super(name); }@Override Public void Add(Component c) {System.out.println ("Can not add a leaf"); }@Override Public void Delete(Component c) {System.out.println ("Can not delete a leaf"); }@Override Public void dispaly(intDepth) {Char[] Ch=New Char[Depth]; for(intI=0; i<depth;i++) {ch[i]='-'; } System.out.println (NewString (CH) +name); }}
Node definition Branch node composite inheritance component.
Public class Composite extends Component{ PrivateList<component> children=NewArraylist<component> (); Public Composite(String name) {Super(name); }@Override Public void Add(Component c) {Children.add (c); }@Override Public void Delete(Component c) {Children.remove (c); }@Override Public void dispaly(intDepth) {Char[] Ch=New Char[Depth]; for(intI=0; i<depth;i++) {ch[i]='-'; } System.out.println (NewString (CH) +name); Iterator<component> Iterator=children.iterator (); while(Iterator.hasnext ()) {Component component=iterator.next (); Component.dispaly (depth+2); } } }
Client code
Public Static void Main(string[] args) {//Combination modeComposite root=NewComposite ("Root"); Root.add (NewLeaf ("Leafa")); Root.add (NewLeaf ("LEAFB")); Composite comp=NewComposite ("Composite X"); Comp.add (NewLeaf ("Leafxa")); Comp.add (NewLeaf ("LEAFXB")); Root.add (comp); Composite comp2=NewComposite ("Composite Y"); Comp2.add (NewLeaf ("Leafxya")); Comp2.add (NewLeaf ("Leafxyb")); Root.add (COMP2); Root.add (NewLeaf ("LEAFC")); Root.dispaly (1);}
Results:
-root
---leafa
---LEAFB
---composite X
-----LEAFXA
-----LEAFXB
---composite Y
-----leafxya
-----LEAFXYB
---LEAFC
Composite mode of design mode (note)