中介者模式通过引入中间人协调对象间通信,降低耦合度,适用于多个对象存在复杂且易变交互的场景,如聊天室、ui控件协同、工作流引擎等;其优点包括解耦同事对象、集中控制交互逻辑、简化对象职责,缺点是中介者可能变得复杂庞大,增加系统抽象层级并带来性能开销;为避免中介者过度复杂,应进行职责分离、使用组合、结合观察者模式或选用其他设计模式,实际应用中需权衡利弊,避免过度设计。

中介者模式,简单来说,就是让一堆对象不用直接互相说话,而是找个“中间人”来传话。用 Golang 实现,能有效降低对象间的耦合度,让系统更灵活。
解决方案
实现中介者模式,核心在于定义一个中介者接口,以及让各个“同事”对象持有该中介者的引用。同事对象间的通信,都通过中介者进行。
立即学习“go语言免费学习笔记(深入)”;
type Mediator interface {
Register(name string, colleague Colleague)
Send(from string, to string, message string)
}type Colleague interface {
Receive(from string, message string)
Send(to string, message string)
SetName(name string)
}type ConcreteMediator struct {
colleagues map[string]Colleague
}
func NewConcreteMediator() *ConcreteMediator {
return &ConcreteMediator{
colleagues: make(map[string]Colleague),
}
}
func (m *ConcreteMediator) Register(name string, colleague Colleague) {
m.colleagues[name] = colleague
colleague.SetName(name)
}
func (m *ConcreteMediator) Send(from string, to string, message string) {
colleague, ok := m.colleagues[to]
if !ok {
fmt.Println("找不到接收者:", to)
return
}
colleague.Receive(from, message)
}type ConcreteColleague struct {
mediator Mediator
name string
}
func NewConcreteColleague(mediator Mediator) *ConcreteColleague {
return &ConcreteColleague{
mediator: mediator,
}
}
func (c *ConcreteColleague) Receive(from string, message string) {
fmt.Printf("%s 收到来自 %s 的消息: %s\n", c.name, from, message)
}
func (c *ConcreteColleague) Send(to string, message string) {
fmt.Printf("%s 发送消息给 %s: %s\n", c.name, to, message)
c.mediator.Send(c.name, to, message)
}
func (c *ConcreteColleague) SetName(name string) {
c.name = name
}func main() {
mediator := NewConcreteMediator()
colleague1 := NewConcreteColleague(mediator)
colleague2 := NewConcreteColleague(mediator)
mediator.Register("Alice", colleague1)
mediator.Register("Bob", colleague2)
colleague1.Send("Bob", "你好,Bob!")
colleague2.Send("Alice", "Alice你好,我是Bob!")
}中介者模式并非银弹,滥用反而会增加系统的复杂性。比较适合的场景是:
在这些场景下,使用中介者模式可以使系统结构更清晰、更易于维护。当然,如果对象之间的交互关系非常简单,或者变化的可能性很小,那么直接让对象互相调用可能更简单直接。
中介者对象承担了协调各个同事对象的职责,很容易变得过于庞大和复杂,成为一个“上帝对象”。避免这种情况,可以考虑以下几点:
总而言之,要根据实际情况,灵活运用设计模式,避免过度设计。
优点:
缺点:
在决定是否使用中介者模式时,需要综合考虑其优缺点,并根据实际情况进行选择。
以上就是怎样用Golang实现中介者模式 减少对象间直接依赖关系的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号