中介者模式是一种行为设计模式, 能让你减少对象之间混乱无序的依赖关系。 该模式会限制对象之间的直接交互, 迫使它们通过一个中介者对象进行合作。

使用场景

中介者模式通常在以下情况下使用:

  1. 引用关系复杂:当系统中对象之间存在复杂的交互关系时,通过引入中介者来简化这些交互,使得系统更加清晰和易于理解。

  2. 改变行为:如果交互的公共行为需要改变,可以增加新的中介者类。中介者模式允许在不影响其他对象的情况下,通过增加新的中介者来改变行为

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import "fmt"

// Mediator 中介者接口
type Mediator interface {
notify(user *User, message string)
}

// ConcreteMediator 具体中介者
type ConcreteMediator struct {
users []*User
}

func (m *ConcreteMediator) addUser(user *User) {
m.users = append(m.users, user)
}

func (m *ConcreteMediator) notify(user *User, message string) {
for _, u := range m.users {
if u != user {
u.receive(message)
}
}
}

// User 用户
type User struct {
name string
mediator Mediator
}

func newUser(name string, mediator Mediator) *User {
return &User{
name: name,
mediator: mediator,
}
}

func (u *User) send(message string) {
fmt.Printf("%s 发送消息:%s\n", u.name, message)
u.mediator.notify(u, message)
}

func (u *User) receive(message string) {
fmt.Printf("%s 收到消息:%s\n", u.name, message)
}

func main() {
mediator := &ConcreteMediator{}

user1 := newUser("Alice", mediator)
user2 := newUser("Bob", mediator)
user3 := newUser("Charlie", mediator)

mediator.addUser(user1)
mediator.addUser(user2)
mediator.addUser(user3)

user1.send("买入股票")
user2.send("卖出股票")
}

结语

中介者模式将对象之间的交互封装起来,使其更加松散耦合,特别是那些具有复杂对象交互关系的系统。通过引入一个中介者,中介者模式将原本对象之间的复杂交互转换为每个对象与中介者之间的交互,从而降低了原有系统的耦合度,使得系统更加灵活且易于扩展。


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。