Video in progress

Strong Middle 🧭 Design patterns

How would you write the Composite pattern for a category tree, and where does it show up in Spring itself?

In Composite, a single element and a group of elements are used through the same interface: the caller doesn't care whether it's dealing with a leaf or a whole branch. In Spring, CompositeCacheManager is built this way, and in Micrometer, CompositeMeterRegistry.

📖 Answer

In a shop, a category contains products and also subcategories. When someone asks for "the number of products in this section", you shouldn't push the recursion onto the caller:

sealed interface CatalogNode permits Product, Category {
    int productCount();
}

record Product(String sku) implements CatalogNode {
    public int productCount() { return 1; }
}

record Category(String name, List<CatalogNode> children) implements CatalogNode {
    public int productCount() {
        return children.stream().mapToInt(CatalogNode::productCount).sum();
    }
}

root.productCount() walks the whole tree by itself. A new aggregate (average price, cheapest product) is also just one more method on this interface.

In Spring and around it:

  • CompositeCacheManager presents several CacheManagers as one and takes the cache from the first manager in the list that has it;
  • Micrometer's CompositeMeterRegistry lets you record a metric in one registry, which forwards it to Prometheus and Datadog alike;
  • HandlerMethodArgumentResolverComposite inside Spring MVC presents a list of resolvers as a single resolver.

What to watch on prod: if the tree comes from the database, a separate query per node gives you N+1. It is better to load the whole tree with one recursive CTE (with recursive) and assemble it in memory. If bad data creates a cycle (a category becomes the parent of its own descendant), the recursion throws a StackOverflowError, so check for cycles when saving.