The schema definition

By using a mediation object to encapsulate (encapsulate changes) a series of object interactions, the mediator makes objects loosely coupled (manage changes) without having to explicitly refer to each other, and can change the interactions between them independently

The class diagram

Application scenarios

Use the mediator pattern to decouple objects when they interact with each other and have complex reference relationships, and when a large number of changes to new requirements are required

advantages

Tightly coupled references between interacting objects can be avoided to better resist change

The point to summarize

The point to summarize

  • By decoupling the complex association relationship between multiple objects, Mediator mode centralizes the control logic among multiple objects, changing “multiple objects are interrelated” to “multiple objects are associated with an intermediary”, simplifying the maintenance of the system and resisting possible changes
  • With the complexity of the control logic, the implementation of the Mediator object may be quite complex, so the Mediator object can be decomposed
  • The Facade pattern decouples (one-way) object relationships between systems, while the Mediator pattern decouples (two-way) object relationships within 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 () { fmt.Println("bill what ?" ) b.mediator.Communicate("bill") } type Ted struct { mediator Mediator } func (t *Ted) Talk () { fmt.Println("Ted : Bill?" ) t.mediator.Communicate("Ted") } func (t *Ted) SetMediator(mediator Mediator) { t.mediator = mediator } func (t *Ted) Respond() { fmt.Println("Ted:how are you today?" ) } type ConcreteMediator struct { Bill Ted } func NewMediator() *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() } }

mediator_test.go

package Mediator

import "testing"

func TestNewMediator(t *testing.T) {
   mediator := NewMediator()
   mediator.Ted.Talk()
}