1组合模式的定义
2.组合模式的UML将对象组合成属性结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
3.代码实现
public abstract Component{
public void someOperation();
public void addChild(Component child){
throw new Exception("叶子不能增加子节点")
}
public void removeChild(child Component){
throw new Exception("叶子无子节点不能删除");
}
public Component getChildren(int index){
throw new Exception("叶子无子借点")
}
}
public class Leaf extends Component{
public void someOperation(){
System.out.println("叶子")
}
}
public class Composite extends Component{
private List<Component> childs=null;
public void someOperation(){
System.out.println("组合");
}
public void addChild(Component child){
if(childs==null){
childs=new ArrayList<Component>();
}
childs.add(child);
}
public void removeChild(Component child){
if(childs!=null){
childs.remove(child)
}
}
public Component getChildren(int index){
if(childs==null || index<0 || childs.size()<=index){
return null;
}
return childs.get(index);
}
}
public class Client{
public static void main(String[] args){
Component root=new Composite();
Component c1=new Composite();
Component c2=new Composite();
Component leaf1=new Leaf();
Component leaf2=new Leaf();
Component leaf3=new Leaf();
root.addChild(c1);
root.addChild(c2);
root.addChild(leaf1);
c1.addChild(leaf2);
c2.addChild(leaf3);
Component o=root.getChildren(1);
o.someOperation();
}
}
4.组合的本质: 统一叶子对象和组合对象