设计模式-组合模式

来源:互联网 发布:js实现动态时钟 编辑:程序博客网 时间:2024/04/30 17:50

原创作品,出自 “晓风残月xj” 博客,欢迎转载,转载时请务必注明出处(http://blog.csdn.net/xiaofengcanyuexj)。

由于各种原因,可能存在诸多不足,欢迎斧正!


     之前在很多场合都看见设计模式的影子,一直以来,都投入主要时间在搞算法与数据结构,后来发现设计模式真的很重要。有的时候代码的可维护、可重用、可扩展确实胜过单纯的算法效率高。所以拾起大牛书籍《大话设计模式》同时参考网上诸大牛的博客,开始我的设计模式之旅。由于平时编程时用C/C++,现在由于将来工作的需要在重新自学Java,也练练Java语法。对于设计模式的重要性,在最近准备做毕业课设时体会尤为深刻:很多时候不是不会编写相关算法模块,而是总感觉自己的代码可读性、可重用性、可拓展性比较差,不利于移植。
     今天先介绍一下组合模式。

1、概念:
     组合模式(Composite):将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

2、实现:

    常见的树结构都有叶节点和分支节点之分,叶节点不包含孩子节点集合,而分支节点包含。                
    

  1)、抽象角色Component:组合中的对象声明接口,也可以为共有接口实现缺省行为。
  2)、叶角色Leaf:在组合中表示叶节点对象,没有子节点,实现抽象构件角色声明的接口。
  3)、枝角色Composite:在组合中表示分支节点对象,有子结构,实现抽象构件角色声明的接口。

3、优点:

      定义了包含基本对象和组合对象的类层次结构,基本对象可以被组合成更复杂的组合对象,而这个组合对象有可以被组合。

4、缺点:

    组合模式不支持动态的插入或删除节点,即不能确定最终到底是分支节点还是叶节点,所以适用范围大大受限,并不能扩展为结构不确定的树结构中。

5、示例代码:

import java.util.ArrayList;/** * Created by xujin on 2014/12/7. */abstract class Component{     String m_strNodeName;    public  Component(String tName)    {        m_strNodeName=tName;    }    public abstract void  add(Component tCom);    public abstract void  delete(Component tCom);    public abstract void  show(int tDepth);}class Leaf extends Component{    public Leaf(String tName)    {        super(tName);    }    public void  add(Component tCom)    {    }    public void delete(Component tCom)    {    }    public void  show(int tDepth)    {        for(int i=0;i<tDepth;++i)            System.out.print("   ");        System.out.println(super.m_strNodeName);    }}class Composite extends Component{    private ArrayList<Component> m_ArrList=new ArrayList<Component>();    public Composite(String tName)    {        super(tName);        m_ArrList.clear();    }    public void  add(Component tCom)    {        m_ArrList.add(tCom);    }    public void delete(Component tCom)    {        int id=m_ArrList.size()-1;        if(id>=0)           m_ArrList.remove(id);    }    public void  show(int tDepth)    {        for(int i=0;i<tDepth;++i)            System.out.print("   ");        System.out.println(super.m_strNodeName);        for(int i=0;i<m_ArrList.size();++i)            m_ArrList.get(i).show(tDepth+1);    }}public class DesirePattern {    public static void main(String []arg)    {        Component root=new Composite("Root");        Component temp1=new Leaf("Leaf");        Component temp2=new Composite("Composite");        Component temp3=new Composite("Composite");        root.add(temp1);        root.add(temp2);        root.add(temp3);        Component temp21=new Leaf("Leaf");        Component temp22=new Leaf("Leaf");        Component temp23=new Leaf("Leaf");        temp2.add(temp21);        temp2.add(temp22);        temp2.add(temp23);        Component temp31=new Leaf("Leaf");        Component temp32=new Leaf("Leaf");        temp3.add(temp31);        temp3.add(temp32);        root.show(0);    }}


       由于时间有限,在写博文的过程中参考过一些文献,在此表示感谢;同时鉴于水平原因,你难免有不足之处,欢迎斧正!

1 0
原创粉丝点击