组合模式,主要构建部件之间的层次关系,主要应用文件和树结构。
public interface Component {
public void add(Component component);
public void remove(Component component);
public void dispaly();
}
public class Composite implements Component {
private List<Component> list = new ArrayList<Component>();
private String name ;
public Composite(String name) {
this .name = name;
}
public void add(Component component) {
list.add(component);
}
public void remove(Component component) {
list.remove(component);
}
public void dispaly() {
System. out .print("composite :" + this. name + "\nleaf: ");
for (Component component : list ) {
System. out .print(component + " " );
}
}
public String toString() {
return this .name ;
}
}
public class Leaf implements Component {
private String name ;
public Leaf(String name) {
this .name = name;
}
public String toString() {
return this .name ;
}
public void add(Component component) {
}
public void remove(Component component) {
}
public void dispaly() {
System. out .print(this .name + " " );
}
}
public class CompositeClient {
public static void main(String[] args) {
Component level1 = new Composite( "level1" );
Component level21 = new Leaf( "level21" );
Component level22 = new Leaf( "level22" );
level1.add(level21);
level1.add(level22);
level1.dispaly();
}
}