美文网首页
设计模式——中介模式

设计模式——中介模式

作者: DevilRoshan | 来源:发表于2020-11-01 02:47 被阅读0次

什么是中介模式

用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

实现

type Mediator interface {
    Comunicate(who string)
}

type Bill struct {
    mediator Mediator
}

func (this *Bill) SetMediator(mediator Mediator) {
    this.mediator = mediator
}

func (this *Bill) Respond() {
    fmt.Println("Bill: what ?")
    this.mediator.Comunicate("Bill")
}

type Ted struct {
    mediator Mediator
}

func (this *Ted) Talk() {
    fmt.Println("Ted:Bill?")
    this.mediator.Comunicate("Ted")
}

func (this *Ted) SetMediator(mediator Mediator) {
    this.mediator = mediator
}


func (this *Ted) Respond() {
    fmt.Println("Ted: How much?")
}

type ConcreteMediator struct {
    Bill
    Ted
}

func NewMediator() *ConcreteMediator {
    mediator := &ConcreteMediator{}
    mediator.Bill.SetMediator(mediator)
    mediator.Ted.SetMediator(mediator)
    return mediator
}

func (this *ConcreteMediator) Comunicate(who string) {
    if who == "Ted" {
        this.Bill.Respond()
    } else {
        this.Ted.Respond()
    }
}
func TestNewMediator(t *testing.T) {
    mediator := NewMediator()
    mediator.Ted.Talk()
}
// === RUN   TestNewMediator
// Ted:Bill?
// Bill: what ?
// Ted: How much?
// --- PASS: TestNewMediator (0.00s)
// PASS

优点

  • 减少类间依赖,降低了耦合;
  • 符合迪米特原则。

缺点

  • 中介者会膨胀的很大,而且逻辑复杂。

使用场景

  • 系统中对象之间存在比较复杂的引用关系;
  • 想通过一个中间类来封装多个类的行为,而又不想生成太多的子类。

注意

  • 不应当在职责混乱时使用。

相关文章

网友评论

      本文标题:设计模式——中介模式

      本文链接:https://www.haomeiwen.com/subject/bdnjvktx.html