结构图
创建下图这个结构
定义一个接口
/**
* Created by lijinquan on 2020/8/28.
*/
public interface Node {
public void print();
}
定义一个枝丫实现Node接口
import java.util.List;
/**
* Created by lijinquan on 2020/8/28.
*/
public class Branch implements Node {
List<Node> nodes=new ArrayList<>();
private String name;
public Branch(String name) {
this.name=name;
}
@Override
public void print() {
System.out.println(name);
}
public void add(Node node){
nodes.add(node);
}
}
再定义一个叶子类实现Node
/**
* Created by lijinquan on 2020/8/28.
*/
public class Leaf implements Node {
private String name;
public Leaf(String name){
this.name=name;
}
@Override
public void print() {
System.out.println(name);
}
}
写一个测试类
package DesignPatterns.com.lijinquan.Composite;
/**
* Created by lijinquan on 2020/8/28.
*/
public class Main {
public static void main(String[] args) {
//实例化一个枝丫bRoot
Branch bRoot = new Branch("bRoot");
//再实例化一个枝丫branch1
Branch branch1 = new Branch("branch1");
//实例化一个叶子leaf1
Leaf leaf1 = new Leaf("leaf1");
//实例化一个叶子leaf2
Leaf leaf2 = new Leaf("leaf2");
//将bRoot当作一个根,下面放入一个枝丫branch1
bRoot.add(branch1);
//枝丫branch1放入两张叶子leaf1 leaf2
branch1.add(leaf1);
branch1.add(leaf2);
tree(bRoot,0);
}
public static void tree(Node node, int depth) {
for(int s=0;s<=depth;s++) System.out.print("--");
node.print();
if (node instanceof Branch) {
Branch b = (Branch) node;
if (b.nodes != null && b.nodes.size() > 0) {
for (int i = 0; i < b.nodes.size(); i++) {
System.out.println("");
tree(b.nodes.get(depth), depth+1);
}
}
}
}
}
运行结果
总结:组合模式主要用来遍历树,你能联想到什么算法呢?