定义:允许你讲对象组合成树的形式结构来表现整体与部分的层次结构。
用途:组合能让客户以一直的方式处理个别对象以及对象组
UML图
Component:
抽象类(接口)定义了4个方法(上图不全)1 add添加一个Component 2 remove删除一个Component 3 取一个Compoent对象 4 功能方法
Leaf:
Extend于Component 主要实现了功能方法
Composit
Extend于Component、实现了Component的四个方法
Composit中有一个list集合用来盛放Component类型的对象、也就是Leaf和Composit、添加、删除、提取某个、这三个方法都是对Leaf的操作。
实现了功能方法、这里不同、他不仅实现了自己的功能、用Iterator遍历了调用了所有枝叶的功能方法。
当添加了一个Composit的对象时候、那个对象同样也能添加Leaf和Composit的对象、也就形成了树形结构、(Leaf可以添加多个)
代码
//抽象类Component
public abstract class Component {
//添加分支
public void add(Component component) {
//没有实现接口或抽象类要求的方法时,抛出异常
throw new UnsupportedOperationException();
}
//删除分支
public void remove(Component component){
throw new UnsupportedOperationException();
}
//取得某个组件
public Component getChild(int i){
throw new UnsupportedOperationException();
}
//输出自己的名字
public void print(){
throw new UnsupportedOperationException();
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class Composite extends Component{
//new一个Component类型的CompositeList、这样叶子节点和分叉都能加进来
ArrayList<Component> compositeList =new ArrayList<Component>();
String name;
//构造方法添加名字
public Composite(String name){
this.name=name;
}
//添加分支实现
public void add(Component component) {
compositeList.add(component);
}
//删除分支实现
public void remove(Component component){
compositeList.remove(component);
}
//取得某个组件实现
public Component getChild(int i){
return (Component)compositeList.get(i);
}
//输出名字
public String getName(){
return name;
}
//输出自己的名字实现/遍历叶子与树枝
public void print(){
System.out.print(getName());
throw new UnsupportedOperationException();
//通过实现Iterator接口实现迭代每个分叉中的叶子与分叉
Iterator iterator = compositeList.iterator();
while(iterator.hasNext()){
Component component=(Component)iterator.next();
component.print();
}
}
}
//叶子类
public class Leaf extends Component{
String name;
//输入名字
public Leaf(String name){
this.name= name;
}
//输出名字
public String getName(){
return name;
}
}
//客户端使用
public class test {
public static void main(String args[]){
//分支与叶子实例化
Component compositeOne =new Leaf("根1");
Component compositeTwo =new Leaf("根2");
Component leafOne =new Leaf("叶子1");
Component leafTwo =new Leaf("叶子2");
compositeOne.add(compositeTwo);//根1添加一个分支
compositeOne.add(leafOne);//根1添加一个叶子
compositeTwo.add(leafTwo);//根2添加一个叶子
compositeOne.print();//输出打印
}
}
考点:
抽象类关键字
继承关键字
组合关系
迭代器(应该不会考吧- -)
——————————最近貌似写博客遇到瓶颈了——————————
————————chenchen————————