如房屋中介,买、卖双方通过中介进行交互
package main
// 如房屋中介
// 买、卖双方通过中介进行交互
// 示例中 Ted 通过中介 与 Bill 问询房屋价格
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 (b *Ted) SetMediator(mediator Mediator) {
b.mediator = mediator
}
func (t *Ted) Respond() {
fmt.Println("Ted: how much?")
}
type Concretemediator struct {
Bill
Ted
}
func (m *Concretemediator) Communicate(who string) {
if who == "Ted" {
m.Bill.Respond()
return
}
m.Ted.Respond()
}
func NewMediator() *Concretemediator {
m := &Concretemediator{}
m.Bill.SetMediator(m)
m.Ted.SetMediator(m)
return m
}
func main() {
m := NewMediator()
m.Ted.Talk()
}
发表回复