English

Artykuł · Kompozyt · Dekorator

Kompozyt (Composite) – drzewa, w których liść i gałąź wyglądają tak samo

Kompozyt pozwala traktować pojedynczy obiekt i całą grupę obiektów w identyczny sposób. Przykład programu kursu z modułami i lekcjami w C#, TypeScript, Javie, Go i Pythonie.

Autor · · 10 min czytania

Menu z podmenu, katalogi z plikami, dział firmy z zespołami, kurs z modułami i lekcjami – drzewa są wszędzie. Kompozyt (ang. Composite) sprawia, że kod operujący na drzewie nie musi pytać „czy to liść, czy gałąź?”: oba mają ten sam interfejs, a gałąź po prostu przekazuje wywołanie swoim dzieciom.

Problem: ile trwa ten kurs?

Platforma kursów programowania pokazuje przy każdym kursie łączny czas nagrań. Kurs składa się z lekcji i sekcji, a sekcje mogą zawierać kolejne sekcje – autorzy lubią „bonusy w bonusach”. Pierwsza implementacja:

course-duration.ts
function totalMinutes(items: (Lesson | Section)[]): number {
  let total = 0;
  for (const item of items) {
    if (item instanceof Lesson) total += item.minutes;
    else if (item instanceof Section) total += totalMinutes(item.children);
    // a new node type (Quiz? LiveSession?) means another branch – here and everywhere else
  }
  return total;
}

Ta sama drabinka instanceof pojawia się w drukowaniu spisu treści, liczeniu lekcji, eksporcie do PDF i sprawdzaniu postępu. Każdy nowy typ węzła – quiz, sesja na żywo – wymaga poprawek we wszystkich tych miejscach.

Rozwiązanie: wspólny interfejs dla liścia i gałęzi

Definiujemy interfejs CurriculumItem z operacjami, które mają sens dla każdego węzła: minutes() i print(). Lesson (liść) odpowiada sam za siebie. Section (kompozyt) trzyma listę dzieci typu CurriculumItem i implementuje te same metody, delegując do dzieci i sumując wyniki. Klient nie odróżnia jednego od drugiego.

Diagram: Struktura Kompozytu

Tak wygląda drzewo z naszego przykładu. Czas każdej sekcji to suma czasów jej dzieci – liczona rekurencyjnie, bez ani jednego instanceof:

Diagram: Przykładowy kurs jako drzewo – sekcje sumują czas dzieci
RolaW przykładzieOdpowiedzialność
Komponent (Component)CurriculumItemwspólny interfejs liści i kompozytów
Liść (Leaf)Lessonwykonuje właściwą pracę, nie ma dzieci
Kompozyt (Composite)Sectionprzechowuje dzieci, deleguje do nich i agreguje wyniki
Klientwidok kursuoperuje na komponentach, nie znając ich rodzaju

Implementacja w pięciu językach

W Javie interfejs jest zapieczętowany (sealed) – kompilator zna wszystkie rodzaje węzłów, co przydaje się przy dopasowaniu wzorców w switch. W Go liść i kompozyt to zwykłe struktury spełniające ten sam interfejs, a w Pythonie wystarczy Protocol.

ICurriculumItem

Curriculum.cs
var course = new Section("Design Patterns",
[
    new Lesson("Welcome", 5),
    new Section("Creational", [new Lesson("Factory Method", 18), new Lesson("Builder", 22)]),
    new Section("Structural",
    [
        new Lesson("Adapter", 15),
        new Section("Bonus", [new Lesson("Composite in UI trees", 12)]),
    ]),
]);

course.Print();
Console.WriteLine($"Total: {course.Minutes} min"); // 72

// Component: a leaf and a branch look the same to the client.
public interface ICurriculumItem
{
    string Title { get; }
    int Minutes { get; }
    void Print(int depth = 0);
}

// Leaf: does the real work.
public sealed record Lesson(string Title, int Minutes) : ICurriculumItem
{
    public void Print(int depth = 0) =>
        Console.WriteLine($"{new string(' ', depth * 2)}- {Title} ({Minutes} min)");
}

// Composite: delegates to its children and aggregates their results.
public sealed class Section(string title, IReadOnlyList<ICurriculumItem> children) : ICurriculumItem
{
    public string Title => title;
    public int Minutes => children.Sum(child => child.Minutes);

    public void Print(int depth = 0)
    {
        Console.WriteLine($"{new string(' ', depth * 2)}+ {Title} ({Minutes} min)");
        foreach (var child in children) child.Print(depth + 1);
    }
}
curriculum.ts
// Component: a leaf and a branch look the same to the client.
interface CurriculumItem {
  readonly title: string;
  minutes(): number;
  print(depth?: number): void;
}

// Leaf: does the real work.
class Lesson implements CurriculumItem {
  constructor(readonly title: string, private readonly length: number) {}

  minutes(): number {
    return this.length;
  }

  print(depth = 0): void {
    console.log(`${"  ".repeat(depth)}- ${this.title} (${this.length} min)`);
  }
}

// Composite: delegates to its children and aggregates their results.
class Section implements CurriculumItem {
  constructor(readonly title: string, private readonly children: CurriculumItem[]) {}

  minutes(): number {
    return this.children.reduce((sum, child) => sum + child.minutes(), 0);
  }

  print(depth = 0): void {
    console.log(`${"  ".repeat(depth)}+ ${this.title} (${this.minutes()} min)`);
    this.children.forEach((child) => child.print(depth + 1));
  }
}

const course = new Section("Design Patterns", [
  new Lesson("Welcome", 5),
  new Section("Creational", [new Lesson("Factory Method", 18), new Lesson("Builder", 22)]),
  new Section("Structural", [
    new Lesson("Adapter", 15),
    new Section("Bonus", [new Lesson("Composite in UI trees", 12)]),
  ]),
]);

course.print();
console.log(`Total: ${course.minutes()} min`); // 72
Curriculum.java
import java.util.List;

// Component: a sealed interface lists every kind of node in the tree.
sealed interface CurriculumItem permits Lesson, Section {
    String title();
    int minutes();
    void print(int depth);
}

// Leaf: does the real work.
record Lesson(String title, int minutes) implements CurriculumItem {
    public void print(int depth) {
        System.out.println("  ".repeat(depth) + "- " + title + " (" + minutes + " min)");
    }
}

// Composite: delegates to its children and aggregates their results.
record Section(String title, List<CurriculumItem> children) implements CurriculumItem {
    public int minutes() {
        return children.stream().mapToInt(CurriculumItem::minutes).sum();
    }

    public void print(int depth) {
        System.out.println("  ".repeat(depth) + "+ " + title + " (" + minutes() + " min)");
        children.forEach(child -> child.print(depth + 1));
    }
}

public class Curriculum {
    public static void main(String[] args) {
        CurriculumItem course = new Section("Design Patterns", List.of(
            new Lesson("Welcome", 5),
            new Section("Creational", List.of(new Lesson("Factory Method", 18), new Lesson("Builder", 22))),
            new Section("Structural", List.of(
                new Lesson("Adapter", 15),
                new Section("Bonus", List.of(new Lesson("Composite in UI trees", 12)))))));

        course.print(0);
        System.out.println("Total: " + course.minutes() + " min"); // 72
    }
}
curriculum.go
package main

import (
	"fmt"
	"strings"
)

// CurriculumItem is the component: a leaf and a branch look the same to the client.
type CurriculumItem interface {
	Minutes() int
	Print(depth int)
}

// Lesson is a leaf: it does the real work.
type Lesson struct {
	Title  string
	Length int
}

func (l Lesson) Minutes() int { return l.Length }

func (l Lesson) Print(depth int) {
	fmt.Printf("%s- %s (%d min)\n", strings.Repeat("  ", depth), l.Title, l.Length)
}

// Section is the composite: it delegates to its children and aggregates their results.
type Section struct {
	Title    string
	Children []CurriculumItem
}

func (s Section) Minutes() int {
	total := 0
	for _, child := range s.Children {
		total += child.Minutes()
	}
	return total
}

func (s Section) Print(depth int) {
	fmt.Printf("%s+ %s (%d min)\n", strings.Repeat("  ", depth), s.Title, s.Minutes())
	for _, child := range s.Children {
		child.Print(depth + 1)
	}
}

func main() {
	course := Section{"Design Patterns", []CurriculumItem{
		Lesson{"Welcome", 5},
		Section{"Creational", []CurriculumItem{Lesson{"Factory Method", 18}, Lesson{"Builder", 22}}},
		Section{"Structural", []CurriculumItem{
			Lesson{"Adapter", 15},
			Section{"Bonus", []CurriculumItem{Lesson{"Composite in UI trees", 12}}},
		}},
	}}
	course.Print(0)
	fmt.Printf("Total: %d min\n", course.Minutes()) // 72
}
curriculum.py
from dataclasses import dataclass, field
from typing import Protocol


class CurriculumItem(Protocol):
    """Component: a leaf and a branch look the same to the client."""

    def minutes(self) -> int: ...
    def print_tree(self, depth: int = 0) -> None: ...


@dataclass(frozen=True)
class Lesson:
    """Leaf: does the real work."""

    title: str
    length: int

    def minutes(self) -> int:
        return self.length

    def print_tree(self, depth: int = 0) -> None:
        print(f"{'  ' * depth}- {self.title} ({self.length} min)")


@dataclass(frozen=True)
class Section:
    """Composite: delegates to its children and aggregates their results."""

    title: str
    children: list[CurriculumItem] = field(default_factory=list)

    def minutes(self) -> int:
        return sum(child.minutes() for child in self.children)

    def print_tree(self, depth: int = 0) -> None:
        print(f"{'  ' * depth}+ {self.title} ({self.minutes()} min)")
        for child in self.children:
            child.print_tree(depth + 1)


if __name__ == "__main__":
    course = Section("Design Patterns", [
        Lesson("Welcome", 5),
        Section("Creational", [Lesson("Factory Method", 18), Lesson("Builder", 22)]),
        Section("Structural", [
            Lesson("Adapter", 15),
            Section("Bonus", [Lesson("Composite in UI trees", 12)]),
        ]),
    ])
    course.print_tree()
    print(f"Total: {course.minutes()} min")  # 72

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Przejrzystość czy bezpieczeństwo?
  • Krok po kroku
  • Kiedy stosować, a kiedy nie
  • Powiązania z innymi wzorcami
  • W praktyce
  • Szybki test
  • Podsumowanie

Załóż darmowe konto · Zaloguj się