Golang设计模式——12中介模式

中介模式

定义

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

优点

  1. 适当地使用中介者模式可以避免同事类之间的过度耦合,使得各同事类之间可以相对独立地使用。
  2. 使用中介者模式可以将对象间一对多的关联转变为一对一的关联,使对象间的关系易于理解和维护。
  3. 使用中介者模式可以将对象的行为和协作进行抽象,能够比较灵活的处理对象间的相互作用。

缺点

  1. 由于中介者承担了较多的责任,所以当中介者被破坏后,各个系统将可能受到影响

场景

一般应用于一组对象以定义良好但是复杂的方式进行通信的场合

代码

在这里插入图片描述

package Mediator

import "fmt"

type Colleague interface {
	Send(msg string)
	Notify(msg string)
	SetMediator(mediator Mediator)
}
type ConcreteColleague1 struct {
	mediator Mediator
}

func (c *ConcreteColleague1) SetMediator(mediator Mediator) {
	c.mediator = mediator
}

func (c *ConcreteColleague1) Send(msg string) {
	c.mediator.Send(msg, c)
}

func (c *ConcreteColleague1) Notify(msg string) {
	fmt.Println("ConcreteColleague1 recv msg:", msg)
}

type ConcreteColleague2 struct {
	mediator Mediator
}

func (c *ConcreteColleague2) SetMediator(mediator Mediator) {
	c.mediator = mediator
}

func (c *ConcreteColleague2) Send(msg string) {
	c.mediator.Send(msg, c)
}

func (c *ConcreteColleague2) Notify(msg string) {
	fmt.Println("ConcreteColleague2 recv msg:", msg)
}

type Mediator interface {
	Send(msg string, colleague Colleague)
}
type ConcreteMediator struct {
	c1 Colleague
	c2 Colleague
}

func (c *ConcreteMediator) Send(msg string, colleague Colleague) {
	if colleague == c.c1 {
		c.c2.Notify(msg)
	} else {
		c.c1.Notify(msg)
	}
}
package Mediator

import "testing"

func TestConcreteMediator_Send(t *testing.T) {
	concreteMediator := &ConcreteMediator{}
	c1 := &ConcreteColleague1{}
	c2 := &ConcreteColleague2{}
	c1.SetMediator(concreteMediator)
	c2.SetMediator(concreteMediator)
	concreteMediator.c1 = c1
	concreteMediator.c2 = c2
	c1.Send("吃饭了吗c2")
	c2.Send("我吃过了c1")
}

其他设计模式

设计模式Git源代码
00简单工厂模式
01工厂方法模式
02抽象工厂模式
03外观模式
04建造者模式
05桥接模式
06命令模式
07迭代器模式
08模板模式
09访问者模式
10备忘录模式
11责任链模式
12中介模式
13原型模式
14状态模式
15策略模式
16享元模式
17组合模式
18解释器模式
19单例模式
20适配器模式
21代理模式
22装饰器模式
23观察者模式

posted @ 2021-09-25 15:06  cheems~  阅读(24)  评论(0编辑  收藏  举报