设计模式-中介者模式

设计模式-中介者模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ChbRgJcf-1660639007579)(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTUgf9NPRYV-3B_8wTKXZ48oiP_X6N8IJUn6g&usqp=CAU)]

参考


中介者模式是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为模式。

使用场景

  • 系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象
  • 通过一个中间类来封装多个类中的行为,而不像生成太多的子类。

Demo分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Eb6hQ1YZ-1660639007580)(C:\Users\86136\AppData\Roaming\Typora\typora-user-images\image-20220816161512141.png)]

分析:

我们通过聊天室实例来演示中介模式。实例中,多个用户可以向聊天室发送消息,聊天室向所有的用户显示消息。我们将创建两个类ChatRoom和User。User对象使用ChartRoom方法来分享它们的消息。

Go实现

package main

import (
	"fmt"
	"time"
)

/**
* 中介类
 */
type ChatRoom struct{}

func (c ChatRoom) Send(user *User, message string) {
	fmt.Printf("%v %s say: %s\n", time.Now(), user.GetName(), message)
}

/**
* 用户类
 */
type User struct {
	Name string
}

func (u *User) GetName() string { return u.Name }

func (u *User) SetName(name string) { u.Name = name }

func (u *User) send(message string) {
	c := ChatRoom{}
	c.Send(u, message)
}

func MediatorPatternDemo() {
	rebort := &User{"Rebort"}
	john := &User{"John"}
	rebort.send("Hello, John")
	john.send("Hello, Rebot")
}

func main() {
	MediatorPatternDemo()
}

输出

2022-08-16 16:22:01.7938729 +0800 CST m=+0.003103101 Rebort say: Hello, John
2022-08-16 16:22:01.8102581 +0800 CST m=+0.019488301 John say: Hello, Rebot

Python实现

import time

class ChatRoom:
  @classmethod
  def SendMessage(self, user, message):
    print(f"{time.time()} {user.getName()} say: {message} ")

class User:
  def __init__(self, name):
    self.name = name

  def getName(self):
    return self.name
  def setName(self, name):
    self.name = name
  def SendMessage(self, message):
    ChatRoom.SendMessage(self, message)

def test():
  rebort = User("rebort")
  john = User("john")
  rebort.SendMessage("hello john")
  john.SendMessage("hi rebort")

if __name__ == '__main__':
  test()

输出

1660638579.3382804 rebort say: hello john 
1660638579.3382804 john say: hi rebort

小结

中介者模式其实就是将类中的方法独立出去,统一进行处理。而独立出去专门处理的部分就是中介者的核心。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值