Design patterns and domain modeling

Composite

Use a common contract for leaves and groups. Executed Java 21 fixture.

Formal Syntax & Structure

java syntaxjava
Group implements Item

Working Example

Example Snippetjava
public class Main {    interface Item { int cents(); }    record Unit(int cents) implements Item {        Unit { if (cents < 0) throw new IllegalArgumentException("price"); }    }    record Group(java.util.List<Item> children) implements Item {        Group { children = java.util.List.copyOf(children); }        public int cents() {            int sum = 0;            for (Item item : children) sum = Math.addExact(sum,item.cents());            return sum;        }    }    public static void main(String[] args) {        Item bundle = new Group(java.util.List.of(new Unit(200),            new Group(java.util.List.of(new Unit(300), new Unit(100)))));        System.out.println(bundle.cents());    }}
Java Reference