组合模式:
树是最常用的一种数据结构了,组合模式就将这种数据结构用到类的组合上。
package composite;
public abstract class Component {
protected String name;
public Component(String name) {
super();
this.name = name;
}
public abstract void add(Component component);
public abstract void removeChildren(Component component);
public abstract void show(int depth);
}
package composite;
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children=new ArrayList<>();
public Composite(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void add(Component component) {
// TODO Auto-generated method stub
children.add(component);
}
@Override
public void removeChildren(Component component) {
// TODO Auto-generated method stub
children.remove(component);
}
@Override
public void show(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print("-");
System.out.println("Composite: " + name);
for(Component component:children) {
component.show(depth+1);
}
}
}
package composite;
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("叶子结点不能增加子节点");
}
@Override
public void removeChildren(Component component) {
// TODO Auto-generated method stub
System.out.println("叶子结点无子节点");
}
@Override
public void show(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
System.out.print("-");
System.out.println("Leaf: " + name);
}
}
package composite;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Component root=new Composite("root");
Component leftchild=new Composite("left child");
Component rightchild=new Composite("right child");
root.add(leftchild);root.add(rightchild);
Component leafA=new Leaf("leaf A");
Component leafB=new Leaf("leaf B");
leftchild.add(leafA); leftchild.add(leafB);
root.show(1);
System.out.println();
leftchild.removeChildren(leafB); root.removeChildren(rightchild);
root.show(1);
}
}
运行
结果:
-Composite: root
--Composite: left child
---Leaf: leaf A
---Leaf: leaf B
--Composite: right child
-Composite: root
--Composite: left child
---Leaf: leaf A
透明方式与安全方式: