[Design Pattern] Strukturelle Muster: Composite

Thomas Darimont

Erfahrenes Mitglied
Hallo,

dieser Beitrag demonstriert das Strukturelle Muster (Structural Pattern): Composite

Das Composite Pattern (Composite = Zusammensetzung, Verbund) beschreibt die Strukturierung von Objekthierarchien derart, dass Benutzer immer mit einer einheitlichen Struktur arbeiten können.

Hier mal ein kleines einfaches Beispiel dazu:
Java:
package de.tutorials.design.patterns.structural;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.jpatterns.gof.CompositePattern;

public class CompositeExample {
  public static void main(String[] args) {

    /*
     * we only work with the interface IPart here.
     * We can compose arbitrarily complex components that can be handled uniformly via the
     * IPart interface.
     */
    IPart partA = new ComplexPart("PartA");
    IPart partB = new ComplexPart("PartB",new ComplexPart("PartBB",new SimplePart("PartBB1")));
    IPart partC = new SimplePart("PartC");
    IPart device = new ComplexPart("component", partA,partB, partC);
    

    device.describe();
  }
  
  @CompositePattern.Leaf
  static interface IPart{
     void describe();
  }
  
  @CompositePattern.Component
  static class SimplePart implements IPart{
    private final String name;

    public SimplePart(String name) {
      this.name = name;
    }

    public String getName() {
      return name;
    }
    
    @Override
    public void describe() {
     System.out.println(getClass().getSimpleName() +": " + getName()); 
    }
  }
  
  @CompositePattern.Composite
  static class ComplexPart extends SimplePart implements Iterable<IPart>{
    private final List<IPart> parts;

    public ComplexPart(String name, IPart ... parts) {
      super(name);
      this.parts = Arrays.asList(parts);
    }
    
    @Override
    public Iterator<IPart> iterator() {
      return parts.iterator();
    }
    
    @Override
    public void describe() {
      super.describe();
      System.out.println("Parts: ");
      for(IPart part : this){
        part.describe();
      }
    }
  }  
}

Ausgabe:
Code:
ComplexPart: component
Parts: 
ComplexPart: PartA
Parts: 
ComplexPart: PartB
Parts: 
ComplexPart: PartBB
Parts: 
SimplePart: PartBB1
SimplePart: PartC


Gruß Tom
 

Neue Beiträge

Zurück