Home  >  Article  >  Java  >  Example analysis of object structure pattern of composition model in Java

Example analysis of object structure pattern of composition model in Java

黄舟
黄舟Original
2017-09-11 10:48:021388browse

This article mainly introduces relevant information about the detailed explanation of the object structure model of the combination model in Java. I hope this article can help everyone understand the application object structure model. Friends in need can refer to it

Detailed explanation of the object structure pattern of the combination model in Java

1. Intention

Combining objects into a tree structure to represent the "part" - "whole" hierarchy. Composite enables users to use single objects and composite objects consistently.

2. Applicability

You want to represent the part-whole hierarchy of objects

You want the user to ignore the combined object Unlike individual objects, users will use all objects in a composite structure uniformly.

3. Structure

##4. Code


public abstract class Component {
  protected String name; //节点名
  public Component(String name){
    this.name = name;
  }

  public abstract void doSomething();
}


public class Composite extends Component {
  /**
   * 存储节点的容器
   */
  private List<Component> components = new ArrayList<>();

  public Composite(String name) {
    super(name);
  }

  @Override
  public void doSomething() {
    System.out.println(name);

    if(null!=components){
      for(Component c: components){
        c.doSomething();
      }
    }
  }

  public void addChild(Component child){
    components.add(child);
  }

  public void removeChild(Component child){
    components.remove(child);
  }

  public Component getChildren(int index){
    return components.get(index);
  }
}


public class Leaf extends Component {


  public Leaf(String name) {
    super(name);
  }

  @Override
  public void doSomething() {
    System.out.println(name);
  }
}


public class Client {
  public static void main(String[] args){
    // 构造一个根节点
    Composite root = new Composite("Root");

    // 构造两个枝干节点
    Composite branch1 = new Composite("Branch1");
    Composite branch2 = new Composite("Branch2");

    // 构造两个叶子节点
    Leaf leaf1 = new Leaf("Leaf1");
    Leaf leaf2 = new Leaf("Leaf2");

    branch1.addChild(leaf1);
    branch2.addChild(leaf2);

    root.addChild(branch1);
    root.addChild(branch2);

    root.doSomething();
  }
}

输出结果:
Root
Branch1
Leaf1
Branch2
Leaf2

The above is the detailed content of Example analysis of object structure pattern of composition model in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn