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观察者模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cheems~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值