Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Merge branch 'master' of https://github.com/VLprojects/semantic into …
…iterator-walk-contract

# Conflicts:
#	design/pattern/README.md
  • Loading branch information
reactivestudio committed Nov 15, 2026
commit 85881d0b537f186d9e8ad4ba9f10b59e2a366d61
134 changes: 132 additions & 2 deletions design/pattern/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ Application Architecture by Fowler in a group of our own, enterprise. A package
a package per pattern inside it. Plain Kotlin, no framework; adapters come as modules of their own.

In place so far: a registry with its store, a registrar and a factory in the creational group;
the contracts of Composite in the structural one; a resolver, the contract of a walk of Iterator and the
base types of Visitor in the behavioral one; the contracts of Plugin in the enterprise one.
the contracts of Composite and Decorator in the structural one; a resolver, the contract of a walk of
Iterator and the base types of Visitor in the behavioral one; the contracts of Plugin in the enterprise one.

## Packages

Expand All @@ -21,6 +21,7 @@ Packages of `semantic-pattern`, under `pro.vlprojects.semantic.pattern`:
| `creational.factory` | `Factory`, an instance made of its definition; `Factory.Definition`, the marker of a definition |
| `creational.factory.error` | `InvalidDefinitionException`; `MultipleFactoriesException`, `FactoryNotFoundException` of a registrar |
| `structural.composite` | `Composite`, the base type of a hierarchy whose containers and leaves a client treats alike; `MutableComposite`, a container whose children change after it is made |
| `structural.decorator` | `Decorator`, a wrapper that holds its component and adds a responsibility to it; `DecoratorFactory`, a component wrapped in a decorator of its type; `AnnotationDecoratorFactory`, a decorator configured by an annotation of the component; `Decorated`, the mark of such an annotation |
| `behavioral.iterator` | `CompositeWalk`, a lazy walk over a `Composite` with `onEnter`, `onLeave` and `maxDepth`; `WalkDirection`, top down or bottom up |
| `behavioral.resolver` | `Resolver`, the values found for a context; `ResolvingPolicy`, one value selected of several, `first` and `last`; `PredicateResolver`, the candidates that hold for a context; `TypeNameResolver`, a subtype by its name |
| `behavioral.resolver.error` | `NotResolvedException`, `MultipleResolvedException` |
Expand Down Expand Up @@ -230,6 +231,135 @@ change of its classes, Flyweight shares its equal parts. A Decorator of the hier
![Flyweight shares equal subtrees](../../docs/assets/composite-flyweight-light.svg#gh-light-mode-only)
![Flyweight shares equal subtrees](../../docs/assets/composite-flyweight-dark.svg#gh-dark-mode-only)

## Decorator

Decorator, as the Gang of Four describe it, attaches a responsibility to an object at run time: a
decorator has the interface of its component, passes each request to it and adds its own work before
or after. Decorators nest, so a set of responsibilities that is not known when the code is compiled is
put together when the application is assembled. Take a decorator away and its responsibility is gone:
the border of a view, the buffer of a stream, as `BufferedInputStream` is. A wrapper whose removal leaves
the work as it was, a check of rights or a cache, controls the access to the object and is a Proxy.

| Role | Who plays it | What it holds |
| --- | --- | --- |
| Component | an interface of the application | the operations |
| ConcreteComponent | a class that implements it | the work itself |
| Decorator | a class that implements `Decorator` and the interface of its component | `delegate`, the wrapped component, and the forwarding of each operation to it |
| ConcreteDecorator | the same class | the operations it overrides, each with its responsibility |

`Decorator<T>` names the role, so a decorator is told from a Proxy by its type, as `SpringProxy` marks a proxy
of Spring AOP. It holds the reference the book calls `_component` as `delegate`, the name CDI gives it with
`@Delegate` and the decorators of Spring give it with `getDelegate()`, `ServerHttpRequestDecorator` of Spring Web
among them. The forwarding of the abstract Decorator of the book is `by` of Kotlin, which writes it for any
interface. The interface of the component a decorator implements itself: a type parameter is no supertype, so
`Decorator<T>` cannot make a class a `T`. `delegate` is public, as a member of an interface is in Kotlin and as
`unwrap` of `java.sql.Wrapper` is, for an adapter or a diagnostic to walk a chain down to the component it
started with. A client depends on the interface of the component, not on `Decorator`: a call through
`delegate` goes round the decorator.

The example of the book, a text view with a scroll bar and a border:

```kotlin
interface VisualComponent {

val text: String

fun draw(): String
}

class ScrollDecorator(override val delegate: VisualComponent) :
VisualComponent by delegate,
Decorator<VisualComponent> {

override fun draw() = this.delegate.draw() + "↕"
}

val window = TextView("text")
.let(::ScrollDecorator)
.let { scroll -> BorderDecorator(scroll, 1) }
```

`window.draw()` is `|text↕|`, and `text` of the window is the one of the view: `by` forwards it.

Each way to write a decorator in Kotlin has a hole the compiler keeps silent about:

- `by` forwards a member that the interface gains later past the decorator: a decorator of metrics does
not time it. Java 8 made the same hole with `removeIf`, a default method that `SynchronizedCollection`
of Commons Collections did not lock, as Effective Java tells in Item 21.
- A decorator without `by` keeps the body that a member has in the interface instead of forwarding it:
a decorator of a `Composite` reads as a leaf unless it overrides `children`.
- A call that the component makes on itself reaches no decorator: the component does not know of them.

A responsibility for every method of many types, metrics or tracing, fits an interceptor bound to an
annotation better: it gets a method that the interface gains later as well, but sees no types. CDI keeps the
two apart in the same way: a decorator knows what the methods it decorates mean, an interceptor does not.

### Factories of decorators

A factory makes a decorator of a ready component, which comes from outside, so a decorator never makes its
component itself:

```kotlin
val scroll = DecoratorFactory<VisualComponent>(::ScrollDecorator)
```

`DecoratorFactory` is named as `HttpHandlerDecoratorFactory` of Spring Web, a `Function<HttpHandler, HttpHandler>`
whose beans Spring WebFlux applies in their order, and `decorate` as `decorate` of Spring `TaskDecorator` and
`Decorate` of Scrutor. Decorator stays the name of the wrapper, as in the book and as Spring Web keeps
`ServerHttpRequestDecorator` apart from the factory. The compiler checks that a factory returns the type of
its component.

### Annotations

`AnnotationDecoratorFactory<A, T>` makes a decorator configured by an annotation of the component. `Decorated` on
an annotation names its factory, as `@Constraint(validatedBy = ...)` of Bean Validation names the
`ConstraintValidator<A, T>` of a constraint and `@Conditional` names the condition of `@ConditionalOnClass` in
Spring Boot:

```kotlin
@Target(AnnotationTarget.CLASS)
@Decorated(BorderDecoratorFactory::class)
annotation class Bordered(val width: Int)

class BorderDecoratorFactory : AnnotationDecoratorFactory<Bordered, VisualComponent> {

override fun decorate(target: VisualComponent, annotation: Bordered) =
BorderDecorator(target, annotation.width)
}

@Bordered(2)
class Caption(text: String) : VisualComponent by TextView(text)
```

An annotation decorates the component it is put on, not each component of a type. It names one factory, so
an annotation is one decorator: several decorators take several annotations. The contracts are plain Kotlin,
as Bean Validation knows no container; an adapter makes the factories and wraps the components.

### Plan of Decorator

1. `Decorator`, `DecoratorFactory`, `AnnotationDecoratorFactory` and `Decorated`.
2. A Spring adapter: a `BeanPostProcessor` wraps a bean by the factories of its type and of its annotations,
as `DataSourceDecoratorBeanPostProcessor` wraps a `DataSource` by its decorators.
- The annotations of a class apply in the order they are written: the top one makes the outermost
decorator, the one a call reaches first, as the top one of stacked decorators of Python and TypeScript
does. JUnit registers several `@ExtendWith` in the order of the source in the same way. Only the
annotations put on the class itself count: inherited and composed ones would mix the order. The
Javadoc of `getAnnotations` promises no order, though javac, the Kotlin compiler and HotSpot keep the
one of the source, so a test of the adapter checks it.
- The factories of a type, which no class names, apply in `@Order`: the first makes the outermost
decorator, as advice of Spring AOP with the lowest `@Order` and `HttpHandlerDecoratorFactory` do.
`CompositeTaskDecorator` of Spring and Scrutor make the first the innermost instead.
- It replaces `@Primary` and `@Qualifier`, where each decorator injects the next by the name of its bean:
a decorator knows neither its neighbours nor its place, a new one goes in between without a change of them,
and the context has no undecorated component to inject by mistake.
- A factory named by an annotation is a bean of its class, as `SpringConstraintValidatorFactory` makes a
validator. A factory of another type than the bean stops the startup with an error of the contract, as
`UnexpectedTypeException` of Bean Validation does. An annotation is looked up on the class of the bean
behind an AOP proxy.
- A bean is replaced by a decorator of its interface: it is injected by the interface, not by its class.
3. Interceptors bound to annotations of methods over `AnnotationMatchingPointcut`, as `@Retryable` of Spring is,
with a check at startup that a proxy reaches each annotated method: Spring only logs a final one.

## Iterator

Iterator, as the Gang of Four describe it, gives the elements of an aggregate one by one and hides
Expand Down
Loading
You are viewing a condensed version of this merge commit. You can view the full changes here.