The Hardest Pattern in Rust: Mediator

A typical Mediator implementation in other languages is a classic anti-pattern in Rust: many objects hold mutable cross-references on each other, trying to mutate each other, which is a deadly sin in Rust - the compiler won't pass your first naive implementation unless it's oversimplified.

The Hardest Pattern in Rust: Mediator
Top-down ownership approach: a mediator takes ownership of all components. Control flow starts from the fn main() where the mediator receives external events/commands.

👉 A code and a full explanation are here: https://github.com/fadeevab/mediator-pattern-rust  (a Train Station example).

Rust rejects a typical approach to implementing some Design Patterns. It's so tricky so I decided to put the whole pattern into a separate repo.

👆 I managed to implement a minimal Mediator pattern example in 2 ways.

  1. A "naive" approach, a reference-counting object model, mimicking a typical OOP language,
  2. top-down ownership approach.

Top-Down Ownership

The key point is thinking in terms of OWNERSHIP.

A top-down ownership approach to implementing Mediator in Rust
  1. A mediator takes ownership of all components.
  2. A component doesn't preserve a reference to a mediator. Instead, it gets the reference via a method call.
  3. Control flow starts from the fn main() where the mediator receives external events/commands.
  4. Mediator trait for the interaction between components is not the same as its external API for receiving external events (commands from the main loop).

What is not covered, at least yet: asynchronous approaches, queue-based event handling with bubble-up capability.