源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2021-05-14 17:21 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java设计模式之组合模式(Composite)
[b]概述[/b] 是一种结构型模式,将对象以树形结构组织起来,以表示“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有唯一性。 UML类图 [img]http://files.jb51.net/file_images/article/201701/201712134826991.jpg?201702134836[/img] 上面的类图包含的角色: [b]Component:[/b]为参加组合的对象声明一个公共的接口,不管是组合还是叶节点。 [b]Leaf:[/b]在组合中表示叶子结点对象,叶子结点没有子结点。 [b]Composite:[/b]表示参加组合的有子对象的对象,并给出树枝构建的行为; [b]代码示例[/b]
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);
  }

}

[b]应用场景[/b] 1.要求表示对象的部分-整体层次结构。 2.想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。 组合模式定义由Leaf对象和Composite对象组成的类结构; 使得客户端变得简单; 它使得添加或删除子部件变得很容易。  以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部