DesignPatternMediator中介者模式

DesignPatternMediator中介者模式

对于一个模块,可能由很多对象构成,而且这些对象之间可能存在相互的引用,为了减少对象两两之间复杂的引用关系,使之称为一个松耦合的系统,这就是中介者模式的模式动机

UML

  • Mediator(抽象中介者):它定义了一个接口,该接口用于与各同事对象之间进行通信。
  • ConcreteMediator(具体中介者):它实现了接口,通过协调各个同事对象来实现协作行为,维持各个同事对象的引用
  • Colleague(抽象同事类):它定义了各个同事类公有的方法,并声明了一些抽象方法来供子类实现,同时维持了一个对抽象中介者类的引用,其子类可以通过该引用来与中介者通信。
  • ConcreteColleague(具体同事类):抽象同事类的子类,每一个同事对象需要和其他对象通信时,都需要先与中介者对象通信,通过中介者来间接完成与其他同事类的通信

实际案例

联合国案例

UML

代码实现

package other

import "fmt"

//实现Mediator以及ConcreteMediator类
type UnitedNations interface {
   ForwardMessage(message string, country Country)
}

type UnitedNationsSecurityCouncil struct {
   USA
   Iraq
}

func (unsc UnitedNationsSecurityCouncil) ForwardMessage(message string, country Country) {
   switch country.(type) {
   case USA:
      unsc.Iraq.GetMessage(message)
   case Iraq:
      unsc.USA.GetMessage(message)
   default:
      fmt.Println("The country is not a member of UNSC")
   }
}

//实现Colleague以及ConcreteColleague类
type Country interface {
   SendMessage(message string)
   GetMessage(message string)
}
type USA struct {
   UnitedNations
}

func (usa USA) SendMessage(message string) {
   usa.UnitedNations.ForwardMessage(message, usa)
}

func (usa USA) GetMessage(message string) {
   fmt.Printf("美国收到对方消息: %s\n", message)
}

type Iraq struct {
   UnitedNations
}

func (iraq Iraq) SendMessage(message string) {
   iraq.UnitedNations.ForwardMessage(message, iraq)
}

func (iraq Iraq) GetMessage(message string) {
   fmt.Printf("伊拉克收到对方消息: %s\n", message)
}

func TTmain() {
   //创建一个具体中介者
   tMediator := &UnitedNationsSecurityCouncil{}
   //创建具体同事,并且让他认识中介者
   tColleageA := USA{
      UnitedNations: tMediator,
   }
   tColleageB := Iraq{
      UnitedNations: tMediator,
   }
   //让中介者认识每一个具体同事
   tMediator.USA = tColleageA
   tMediator.Iraq = tColleageB
   //A同事发送消息
   tColleageA.SendMessage("停止核武器研发,否则发动战争")
   tColleageB.SendMessage("我们没有研发核武器,也不怕战争")
}


# 测试ttmain()输出
伊拉克收到对方消息: 停止核武器研发,否则发动战争
美国收到对方消息: 我们没有研发核武器,也不怕战争
posted @ 2020-12-11 09:52  maob  阅读(80)  评论(0编辑  收藏  举报