1
0
Fork 0
design-patterns/go/mediator/main.go

98 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"fmt"
"slices"
)
/*
实例:
汤宝宝一时想不开,当了房产中介。
他负责把房东和租客撮合在一起,帮他们达成租房协议。
*/
// 抽象中介者
type Mediator interface {
register(colleague Colleague)
Notify(sender Colleague, event string)
}
// 具体中介者 - 房产中介
type HousingMediator struct {
colleagues []Colleague
}
func (m *HousingMediator) register(colleague Colleague) {
if slices.Contains(m.colleagues, colleague) {
return // 已注册
}
m.colleagues = append(m.colleagues, colleague)
}
func (m *HousingMediator) Notify(sender Colleague, event string) {
for _, colleague := range m.colleagues {
if colleague != sender {
colleague.Receive(event)
}
}
}
// 抽象同事类
type Colleague interface {
Send(event string)
Receive(event string)
}
// 具体同事类 - 房东
type Landlord struct {
mediator Mediator
name string
}
func (l *Landlord) Send(event string) {
fmt.Printf("房东%s发布信息: %s\n", l.name, event)
l.mediator.Notify(l, event)
}
func (l *Landlord) Receive(event string) {
fmt.Printf("房东%s收到通知: %s\n", l.name, event)
}
// 具体同事类 - 租客
type Tenant struct {
mediator Mediator
name string
}
func (t *Tenant) Send(event string) {
fmt.Printf("租客%s发布需求: %s\n", t.name, event)
t.mediator.Notify(t, event)
}
func (t *Tenant) Receive(event string) {
fmt.Printf("租客%s收到通知: %s\n", t.name, event)
}
func main() {
fmt.Println("============= 中介者模式 =============")
mediator := &HousingMediator{}
landlord1 := &Landlord{mediator: mediator, name: "张三"}
landlord2 := &Landlord{mediator: mediator, name: "李四"}
tenant1 := &Tenant{mediator: mediator, name: "王五"}
tenant2 := &Tenant{mediator: mediator, name: "赵六"}
mediator.register(landlord1)
mediator.register(landlord2)
mediator.register(tenant1)
mediator.register(tenant2)
landlord1.Send("张三有一套两室一厅的房子出租月租2000元。")
fmt.Println("-----")
tenant1.Send("王五需要一套三室的房子预算3000元/月。")
fmt.Println()
fmt.Println("=========== 中介者模式结束 ===========")
}