二十一、mediator 中介者模式
作为中介者, 协调各对象
https://refactoringguru.cn/design-patterns/mediator
21.1 bus_mediator
https://refactoringguru.cn/design-patterns/mediator/go/example
车站作为中介者, 协调各车
├── bus.go
├── mediator.go
├── mediator_test.go
└── readme.md
21.1.1 mediator_test.go
package _11bus_station
import "testing"
/*
=== RUN TestMediator
passengerBus 成功到达
goodBus 成功到达
passengerBus 成功出发
广播消息: &{0x140001320a8} 已经到达
广播消息: &{0x140001320a8} 已经到达
--- PASS: TestMediator (0.00s)
PASS
*/
func TestMediator(t *testing.T) {
m := &busMediator{buses: make([]bus, 0)}
b1 := &passengerBus{m}
b1.arrive()
b2 := &goodBus{m}
b2.arrive()
b1.depart()
}
21.1.2 mediator.go
package _11bus_station
import (
"fmt"
)
type mediator interface {
canArrive(bus) bool
notifyDepart()
}
type busMediator struct {
buses []bus
}
func (m *busMediator) canArrive(b bus) bool {
m.buses = append(m.buses, b)
return true
}
func (m *busMediator) notifyDepart() {
for _, b := range m.buses {
fmt.Printf("广播消息: %v 已经到达\n", b)
}
}
21.1.3 bus.go
package _11bus_station
import "fmt"
type bus interface {
// 到达
arrive()
// 出发
depart()
}
// 载人 bus
type passengerBus struct {
mediator mediator
}
func (b *passengerBus) arrive() {
if !b.mediator.canArrive(b) {
fmt.Println("passengerBus 无法到达")
return
}
fmt.Println("passengerBus 成功到达")
}
func (b *passengerBus) depart() {
fmt.Println("passengerBus 成功出发")
b.mediator.notifyDepart()
}
// 载货 bus
type goodBus struct {
mediator mediator
}
func (b *goodBus) arrive() {
if !b.mediator.canArrive(b) {
fmt.Println("goodBus 无法到达")
return
}
fmt.Println("goodBus 成功到达")
}
func (b *goodBus) depart() {
fmt.Println("goodBus 成功出发")
b.mediator.notifyDepart()
}