设计模式之---组合模式
定义
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objectsand compositions of objects uniformly.
将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
类图:略
从类图组合模式主要三个功能类
- 抽象构建类 Component
- 叶子构建类 Leaf
- 树枝构建类 Composite
优点
- 便于业务层的调用
- 叶子和树枝构件自由增加
缺点
- 和依赖倒置原则相违背,因为其依赖了具体的实现类
代码
public abstract class Component {
public void doSomething(){
}
}
public class Composite extends Component {
private List components=new ArrayList();
public void add(Component component){
this.components.add(component);
}
public void remove(Component component){
this.components.remove(component);
}
public List getChildren(){
return this.components;
}
@Override
public void doSomething() {
super.doSomething();
System.out.println("我是父节点");
}
}
public class Leaf extends Component {
@Override
public void doSomething() {
super.doSomething();
System.out.println("我是叶构件");
}
}
测试类
public class Test {
public static void main(String[] args) {
Composite root=new Composite();
Composite branch=new Composite();
Leaf leaf=new Leaf();
root.add(branch);
branch.add(leaf);
display(root);
}
public static void display(Composite root){
for (Component c:root.getChildren()){
if(c instanceof Leaf){
c.doSomething();
}else{
display((Composite) c);
}
}
}
}
输出结果
我是叶构件
参考:百度百科