Java设计模式----组合模式(Composit )

来源:互联网 发布:linux中grep命令详解 编辑:程序博客网 时间:2024/06/06 04:37

1.  组合模式定义:

    组合模式,又叫合成模式,有时又叫部分-整体模式,主要用来描述部分与整体的关系。

    定义:将对象组合成树形结构以示“ 部分--整体 ”的层次结构,使得用户对单个对象的使用具有一致性。

2.  组合模式的3个对象:

    a.  Component 抽象构件角色

     定义参加组合对象的共有的属性和方法,可以定义一些默认的行为或属性

    b.  Leaf 叶子构件

     叶子对象,其下再无分支,也是遍历的最小单位

    c.  Composit 树枝构件

    树枝对象,作用是组合树枝构件和叶子构件,形成树形结构

3. 组合模式通用示例代码:

  Component类: 

public abstract class Component {  //个体和整体都具有的共享public void  doSomething(){System.out.println("大家都有的...");}}
 NewLeaf  叶子构件类:

public class NewLeaf extends Component {   @Overridepublic void doSomething() {super.doSomething();System.out.println("叶子节点才有的.");}}
 Composit 树枝构件类
public class Composit extends Component {    //构建容器private ArrayList<Component> list=new ArrayList<Component>();//增加一个叶子节点或树枝节点public void  add(Component com){this.list.add(com);}//删除节点public void  remove(Component com){this.list.remove(com);}//获得当前分支下的所有叶子节点和树枝节点public ArrayList<Component> getChildren(){return this.list;}}
测试代码:

public class Test {   public static void main(String[] args) {//创建根节点Composit root=new Composit();root.doSomething();//创建一个树枝节点Composit branch=new Composit();//创建一个叶子节点NewLeaf leaf=new NewLeaf();root.add(branch);branch.add(leaf);display(root);   }      public static void display(Composit root){   for (Component it : root.getChildren()) {if(it instanceof NewLeaf){it.doSomething();}else{display((Composit)it);}   }   }}
4.  组合模式的优点:

   a. 高层模块调用简单

   一棵树的所有节点都是Component,局部和整体对调用者来说并没有区别,也就是说,高层不必关心是在处理单个对象还是组合结构,简化了高层模块的代码。

   b. 节点自由增加

   如果要增加一个树枝节点或者树叶节点,只需要找到它的父节点即可。非常容易扩展,符合开闭原则。

5.  组合模式的缺点:

  从测试类明显可以看出,在使用树叶和树枝定义时直接使用了实现类,而不是接口,与依赖倒置原则冲突!

6.  组合模式的使用场景:

   a.  维护” 部分-整体“关系的场景,如树形菜单,文件和文件夹处理

   b.  从一个整体中能够独立出部分模块和功能的场景


0 0