Mediator 中介者
动机(Motivation)
在软件构建过程中,经常会出现多个对象互相关联交互的情况,对象之间常常会维持一种复杂的引用关系,如果遇到一些需求的更改,这种直接的引用关系将面临不断的变化。
在这种情况下,我们可以使用一个“中介对象”来管理对象间的关联关系,避免相互交互的对象之间的紧耦合引用关系,从而更好的抵御变化。
模式变化
用一个中介对象来封装(封装变化)一系列的对象交互。中介者使各对象不需要显式的相互引用(编译时依赖→运行时依赖),从而使其耦合松散(管理变化),而且可以独立地改变它们之间的交互。
——《设计模式》GoF
要点总结
将多个对象间复杂的关联关系解耦,Mediator模式将多个对象间的控制逻辑进行集中管理,变“多个对象互相关联”为“多个对象和一个中介者关联”,简化了系统的维护,抵御了可能的变化。
随着控制逻辑的复杂化,Mediator具体对象的实现可能相当复杂。
这时候可以对Mediator对象进行分界处理。
Facade模式是解耦系统间(单向)的对象关联关系;Mediator模式是解耦系统内各个对象之间(双向)的关联关系。
package main
import (
"fmt"
)
// Mediator 设计模式
// 定义一个Mediaoter interface
type Mediator interface {
// 转发
Relay(c Colleague,msg string)
// 注册 Colleague
Register(c Colleague)
}
type ConcreteMediator struct {
colleagues []Colleague
}
func (c *ConcreteMediator) Register(col Colleague){
c.colleagues = append(c.colleagues, col)
}
func (c *ConcreteMediator) Relay(col Colleague,msg string){
for _,v := range c.colleagues{
if v == col && v != nil{
v.Receive(msg)
}
}
}
// 定一个Colleague interface
type Colleague interface {
// 发送消息
Send(col Colleague, msg string)
// 接受消息
Receive(msg string)
}
// 定义一个ColleagueA
type ColleagueA struct {
m Mediator
}
func (c *ColleagueA) Send(col Colleague, msg string){
fmt.Printf("ColleagueA send msg->%s\n",msg)
c.m.Relay(col,msg)
}
func (c *ColleagueA) Receive(msg string){
fmt.Printf("ColleagueA receive msg is %s\n",msg)
}
// 定义一个ColleagueB
type ColleagueB struct {
m Mediator
}
func (c *ColleagueB) Send(col Colleague, msg string){
fmt.Println("ColleagueB send msg")
c.m.Relay(col,msg)
}
func (c *ColleagueB) Receive(msg string){
fmt.Printf("ColleagueB receive msg is %s\n",msg)
}
func main(){
cm := ConcreteMediator{}
c1 := ColleagueA{}
c2 := ColleagueB{}
cm.Register(&c1)
cm.Register(&c2)
c1.m = &cm
c1.Send(&c2, "i am justin sun")
}