composition Pattern definition: Combines objects into a tree structure to represent a "partial-whole" hierarchy, which makes the user consistent with the use of individual objects and composite objects.
Advantages:
1, high-level module call simple.
2, the node is free to add.
Disadvantages:
The use of leaves and branches is an implementation class that violates the concept of interface-oriented programming and conflicts with the principle of dependency inversion.
The class diagram is as follows:
The implementation code is as follows:
Component Abstract Component roles:
Package com.designpatterns.composite;/** * @author WSYW126 * @version May 6, 2016 PM 6:48:31 */public abstract class Componen t {public abstract void dosomething ();}
Leaf component of Leaf:
Package com.designpatterns.composite;/** * @author WSYW126 * @version May 6, 2016 PM 6:52:37 */public class Leaf extends Compo nent {@Overridepublic void dosomething () {System.out.println ("I am leaf!");}}
Composite Branch Components:
Package Com.designpatterns.composite;import java.util.arraylist;/** * @author WSYW126 * @version May 6, 2016 6:49:35 * * public class Composite extends Component {private arraylist<component> list = new arraylist<> ();p ublic void ad D (Component Component) {list.add (Component);} public void Remove (Component Component) {list.remove (Component);} Public arraylist<component> GetChildren () {return this.list;} @Overridepublic void DoSomething () {System.out.println ("I am branch!");}}
Test class:
Package com.designpatterns.composite;/** * @author WSYW126 * @version May 6, 2016 PM 6:52:53 */public class Client {public STA tic void Main (string[] args) {Composite root = new Composite (); root.dosomething (); Composite branch = new Composite (); Leaf leaf = new Leaf (), Root.add (branch), Branch.add (leaf);d isplay (root); Recursive traversal tree private static void display (Composite root) {for (Component C:root.getchildren ()) {if (c instanceof Leaf) {C.dosome Thing ();} else {display ((Composite) c);}}}}
This is the combination pattern.
References :
The Zen of design pattern
Remark :
Reprint please indicate the source
http://blog.csdn.net/wsyw126/article/details/51333823
by WSYW126
The combination mode of design pattern