当前位置: 移动技术网 > IT编程>开发语言>Java > java设计模式之组合模式(Composite)

java设计模式之组合模式(Composite)

2019年07月22日  | 移动技术网IT编程  | 我要评论

概述

是一种结构型模式,将对象以树形结构组织起来,以表示“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有唯一性。

uml类图

上面的类图包含的角色:

component:为参加组合的对象声明一个公共的接口,不管是组合还是叶节点。
leaf:在组合中表示叶子结点对象,叶子结点没有子结点。
composite:表示参加组合的有子对象的对象,并给出树枝构建的行为;

代码示例

import java.util.arraylist;
import java.util.list;

abstract class component {

  protected string name;

  public component(string name) {
    this.name = name;
  }

  public abstract void add(component c);

  public abstract void remove(component c);

  public abstract void getchild(int depth);
}

class leaf extends component {

  public leaf(string name) {
    super(name);
  }

  @override
  public void add(component c) {
    system.out.println("can not add to a leaf");
  }

  @override
  public void remove(component c) {
    system.out.println("can not remove from a leaf");
  }

  @override
  public void getchild(int depth) {
    string temp = " ";
    for (int i = 0; i < depth; i++) {
      temp += "-";
      system.out.println(temp + name);
    }
  }

}

class composite extends component {

  private list<component> children = new arraylist<>();

  public composite(string name) {
    super(name);
  }

  @override
  public void add(component c) {
    children.add(c);
  }

  @override
  public void remove(component c) {
    children.remove(c);
  }

  @override
  public void getchild(int depth) {

    for (component c : children) {
      c.getchild(depth);
    }
  }

}

public class main {

  public static void main(string args[]) {
    composite root = new composite("root");
    root.add(new leaf("leaf a"));
    root.add(new leaf("leaf b"));

    composite compx = new composite("composite x");
    compx.add(new leaf("leaf xa"));
    compx.add(new leaf("leaf xb"));
    root.add(compx);

    composite compxy = new composite("composite xy");
    compxy.add(new leaf("leaf xya"));
    compxy.add(new leaf("leaf xyb"));
    compx.add(compxy);

    root.getchild(3);
  }

}

应用场景

1.要求表示对象的部分-整体层次结构。
2.想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。

组合模式定义由leaf对象和composite对象组成的类结构;
使得客户端变得简单;
它使得添加或删除子部件变得很容易。

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网