The schema definition
Using a mediation object to encapsulate (encapsulate change) a set of object interactions, the mediator makes objects loose (manage change) by not having to explicitly refer to each other, and can change their interactions independently
The class diagram
Application scenarios
The mediator pattern is used for decoupling when multiple objects interact with each other and have complex reference relationships, and when significant changes are required to new requirements
advantages
You can better resist change by avoiding tightly coupled reference relationships between interacting objects
The point to summarize
The point to summarize
- The complex association relationship between multiple objects is decoupled. Mediator mode centrally manages the control logic between multiple objects, changing “association between multiple objects” to “association between multiple objects and an intermediary”, simplifying the maintenance of the system and resisting possible changes
- With the complexity of control logic, the implementation of Mediator object may be quite complicated. At this time, the Mediator object can be decomposed
- Facade mode decoupled the (one-way) association of objects between systems, while Mediator mode decoupled the (two-way) association between objects in the system
Go language code implementation
Project directory
mediator.go
package Mediator
import "fmt"
type Mediator interface {
Communicate (who string)}type WildStallion interface {
SetMediator(mediator Mediator)
}
type Bill struct {
mediator Mediator
}
func (b * Bill) SetMediator(mediator Mediator) {
b.mediator = mediator
}
func (b * Bill) Respond (a) {
fmt.Println("bill what ?")
b.mediator.Communicate("bill")}type Ted struct {
mediator Mediator
}
func (t *Ted) Talk (a) {
fmt.Println("Ted : Bill?")
t.mediator.Communicate("Ted")}func (t *Ted) SetMediator(mediator Mediator) {
t.mediator = mediator
}
func (t *Ted) Respond(a) {
fmt.Println("Ted:how are you today?")}type ConcreteMediator struct {
Bill
Ted
}
func NewMediator(a) *ConcreteMediator {
mediator := &ConcreteMediator{}
mediator.Bill.SetMediator(mediator)
mediator.Ted.SetMediator(mediator)
return mediator
}
func (m *ConcreteMediator) Communicate(who string) {
if who == "Ted" {
m.Bill.Respond()
}else {
m.Ted.Respond()
}
}
Copy the code
mediator_test.go
package Mediator
import "testing"
func TestNewMediator(t *testing.T) {
mediator := NewMediator()
mediator.Ted.Talk()
}
Copy the code