• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
组合模式

组合模式的定义:
主要用来描述部分和整体的关系,其定义如下:
Compose objects into tree structure to represent part-whole hierarchies. Composite lets clients treat
individual objects and compositions of objects uniformly.
将对象组合成树形结构以表示“部分——整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

组合模式的角色:
1.Component抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性
2.Leaf叶子构件
叶子对象,其下面也没有其他分支,也就是遍历的最小单位
3.Composite树枝构件
树枝对象,它的作用是组合树枝节点或叶子节点形成一个树形结构

//抽象构件
public abstract class Component{
    public void doSomething(){
        //
    }
}
//树枝构件
public class Composite extends Component{
    private ArrayList<Component> componentArrayList=new ArrayList<Component>();
    public void add(Component component){
        this.componentArrayList.add(component);
    }
    public void remove(Component component){
        this.componentArrayList.remove(component);
    }
    public ArrayList<Component> getChildren(){
        return this.componentArrayList;
    }
}

//树叶构件
public class Leaf extends Component{
    /*
     *可以覆盖父类方法
    public void doSomething(){
    
    }
    */
}

//场景类
public class Client{
    public static void main(String[] args){
        //创建一个根节点
        Composite root=new Composite();
        root.doSomething();
        //构建一个树形节点
        Composite branch=new Composite();
        Leaf leaf=new Leaf();
        //建立整体
        root.add(branch);
        branch.add(leaf);
    }
    
    //通过递归遍历树
    public static void display(Composite root){
        for(Component c:root.getChildren()){
            if(c instanceof Leaf){//叶子节点
                c.doSomething();
            }else{//树枝节点
                display((Composite)c);
            }
        }
    }
}

 

posted on 2016-05-14 19:11  山高我为峰  阅读(219)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3