Chapter 19: Mediator Pattern
大綱
When should you use it?
The mediator pattern is a behavioral design pattern that encapsulates how objects communicate with one another.
The colleagues: the objects that want to communicate with each other. They implement the colleague protocol.
The colleague protocol: defines methods and properties that each colleague must implement.
The mediator: the object that controls the communication of the colleagues. It implements the mediator protocol.
The mediator protocol: defines methods and properties that the mediator must implement.

When should you use it?
This pattern is especially useful when you need one or more colleagues to act upon events initiated by another colleague, and, in turn, have this colleague generate further events that affect other colleagues.
Playground example
結果
Step1: 實作Colleague Protocol
Step2: 實作Mediator Protocol
Step3: 實作Colleague
Step4: 實作Mediator
What should you be careful about?
This pattern is very useful in decoupling colleagues.
Instead of colleagues interacting directly, each colleague communicates through the mediator.
Be careful about turning the mediator into a “god” object — an object that knows about every other object within a system.
If your mediator gets too big, consider breaking it up into multiple mediator–colleague systems
Tutorial project
目標: This app will help users plan a date that involves three different locations: a bar, restaurant and movie theater.
Key points
The mediator pattern encapsulates how objects communicate with one another. It involves four types: colleagues, a colleague protocol, a mediator, and a mediator protocol.
The colleagues are the objects that communicate; the colleague protocol defines methods and properties all colleagues must have; the mediator controls the communication of the colleagues; and the mediator protocol defines required methods and properties that the mediator must have.
In lieu of talking directly, colleagues hold onto and communicate through the mediator. The colleague protocol and mediator protocol helps prevent tight coupling between all objects involved.”
Last updated