纵有疾风起
人生不言弃

设计模式九–组合模式

定义

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

角色

1:抽象构建(Component)角色
该角色定义参加组合对象的共有方法和共有属性,规范一些默认的行为接口

public interface Component{  public void operation();} 

2:叶子构建(Leaf)角色
该角色是叶子对象,其下没有其他的分支,定义出参加组合的原始对象的行为

public class Leaf implements Component{  @Override  public void operation()  {  }}

3:树枝构建(Composite)角色
该角色代表参加组合的、其下所有分支的树枝对象,它的作用是将树枝和叶子组合成一个树形结构,并定义出管理子对象的方法

public class Composite implements Component{   //子节点容器  private ArrayList  <Component> componentList = new ArrayList<Component> ();  //添加构件  public void add(Component c){    this.componentList.add(c);  }  //删除构件  public void remove(Component c){    this.componentList.remove(c);  }  //获取子构件  public ArrayList<Component> getChild(){    return this.componentList;  }  @Override  public void operation(){  }}

调用示例

public class Client{  public static void main(String [] args){     //创建根节点    Composite root = new Composite();      root.operation();    //创建子节点和叶子节点    Composite branch = new Composite();    Leaf leaf = new Leaf();    挂载    root.add(branch);    branch.add(leaf);  }  public static void display(Composite root){    for(Component c : root.getChild()){      // 如果是叶子就直接执行逻辑      if(c instanceof Leaf){        c.operation();        }else{       // 如果不是叶子就执行逻辑以后递归遍历        c.operation();        display((Component) c);      }    }  }}

优点

1:高层模块调用简单
2:节点增加自由

缺点

1:不易控制树枝构件类型
2:不易使用继承方法来增加新的行为

使用场景

1:需要描述对象层级关系(文件目录等等)
2:需要忽略个体和整体的区别,平等对待所有组件的

参考资料:设计模式(java)

文章转载于:https://www.jianshu.com/p/77393679654a

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » 设计模式九–组合模式
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录