文档查阅说明:
定义:将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性
使用场景:
● Component抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性,比如我们例子中的getInfo就封装到了抽象类中。
● Leaf叶子构件
叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。
● Composite树枝构件
树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构
public abstract class Component {
private String name;
public Component(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display(int depth);
}
public class Composite extends Component {
public Composite(String name) {
super(name);
// TODO Auto-generated constructor stub
}
private List<Component> children = new ArrayList<>();
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public void display(int depth) {
String tmp = "-";
for(int i =0; i< depth; i++) {
System.out.print("-");
}
System.out.println(this.getName());
for(Component component:children){
component.display(depth + 2);
}
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void add(Component component) {
// TODO Auto-generated method stub
System.out.println("cannot add a leaf");
}
@Override
public void remove(Component component) {
// TODO Auto-generated method stub
System.out.println("cannot remove from a leaf");
}
@Override
public void display(int depth) {
// TODO Auto-generated method stub
String tmp = "-";
for(int i =0; i< depth; i++) {
System.out.print("-");
}
System.out.println(this.getName());
}
}
public class Test {
public static void main(String[] args) {
Composite root = new Composite("root");
root.add(new Leaf("A"));
root.add(new Leaf("B"));
Composite comp = new Composite("X");
comp.add(new Leaf("X.A"));
comp.add(new Leaf("X.B"));
root.add(comp);
Composite comp2 = new Composite("Y");
comp2.add(new Leaf("Y.A"));
Composite comp3 = new Composite("Z");
comp3.add(new Leaf("Z.A"));
comp3.add(new Leaf("Z.B"));
comp2.add(new Leaf("Y.B"));
comp2.add(comp3);
root.add(comp2);
root.add(new Leaf("C"));
root.display(1);
}
}