缘起

最近复习设计模式
拜读谭勇德的<<设计模式就该这样学>>
本系列笔记拟采用golang练习之

中介者模式

  1. 中介者模式(Mediator Pattern)又叫作调解者模式或调停者模式。
  2. 用一个中介对象封装一系列对象交互,
  3. 中介者使各对象不需要显式地相互作用,
  4. 从而使其耦合松散,
  5. 而且可以独立地改变它们之间的交互,
  6. 属于行为型设计模式。
  7. 中介者模式主要适用于以下应用场景。
  8. 1)系统中对象之间存在复杂的引用关系,产生的相互依赖关系结构混乱且难以理解。
  9. 2)交互的公共行为,如果需要改变行为,则可以增加新的中介者类。
  10. (摘自 谭勇德 <<设计模式就该这样学>>)

场景

  • 某物联网企业, 研发各种智能家居产品, 并配套手机app以便用户集中控制
  • 一开始的设计是手机app通过本地局域网的广播协议, 主动发现/注册/控制各种智能设备
  • 后来智能设备的种类越来越多, 通信协议多种多样, 导致手机app需要频繁升级, 集成过多驱动导致代码膨胀
  • 研发部门痛定思痛, 决定采用中介者模式重新设计整个系统架构
  • 老架构: app -> 智能设备*N
  • 新架构: app -> 云中心 -> 智能设备
  • 通过引入”云中心” 作为中介, 将app与设备驱动解耦
  • app与云中心采用RESTFul协议通信, 极大提升开发运维的效率

设计

  • MockPhoneApp: 虚拟的手机app, 用于跟云中心通信, 控制智能设备
  • ICloudMediator: 云中心面向手机app的接口
  • ICloudCenter: 云中心面向智能设备的注册接口
  • ISmartDevice: 智能设备接口
  • tMockCloudMediator: 虚拟的云中心服务类, 面向手机app实现ICloudMediator接口, 面向智能设备实现ICloudCenter接口
  • tMockSmartLight: 虚拟的智能灯设备, 实现ISmartDevice接口

单元测试

mediator_pattern_test.go

  1. package behavioral_patterns
  2. import (
  3. "learning/gooop/behavioral_patterns/mediator"
  4. "testing"
  5. )
  6. func Test_MediatorPattern(t *testing.T) {
  7. // 设备注册
  8. center := mediator.DefaultCloudCenter
  9. light := mediator.NewMockSmartLight(1)
  10. center.Register(light)
  11. fnCallAndLog := func(fn func() error) {
  12. e := fn()
  13. if e != nil {
  14. t.Log(e)
  15. }
  16. }
  17. // 创建app
  18. app := mediator.NewMockPhoneApp(mediator.DefaultCloudMediator)
  19. // 设备控制测试
  20. fnCallAndLog(func() error {
  21. return app.LightOpen(1)
  22. })
  23. fnCallAndLog(func() error {
  24. return app.LightSwitchMode(1, 1)
  25. })
  26. fnCallAndLog(func() error {
  27. return app.LightSwitchMode(1, 2)
  28. })
  29. fnCallAndLog(func() error {
  30. return app.LightClose(1)
  31. })
  32. }

测试输出

  1. t$ go test -v mediator_pattern_test.go
  2. === RUN Test_MediatorPattern
  3. tMockSmartLight.open, id=1
  4. tMockSmartLight.switchMode, id=1, mode=1
  5. tMockSmartLight.switchMode, id=1, mode=2
  6. tMockSmartLight.close, id=1
  7. --- PASS: Test_MediatorPattern (0.00s)
  8. PASS
  9. ok command-line-arguments 0.002s

MockPhoneApp.go

虚拟的手机app, 用于跟云中心通信, 控制智能设备

  1. package mediator
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type MockPhoneApp struct {
  7. mediator ICloudMediator
  8. }
  9. func NewMockPhoneApp(mediator ICloudMediator) *MockPhoneApp {
  10. return &MockPhoneApp{
  11. mediator,
  12. }
  13. }
  14. func (me *MockPhoneApp) LightOpen(id int) error {
  15. return me.lightCommand(id, "light open")
  16. }
  17. func (me *MockPhoneApp) LightClose(id int) error {
  18. return me.lightCommand(id, "light close")
  19. }
  20. func (me *MockPhoneApp) LightSwitchMode(id int, mode int) error {
  21. return me.lightCommand(id, fmt.Sprintf("light switch_mode %v", mode))
  22. }
  23. func (me *MockPhoneApp) lightCommand(id int, cmd string) error {
  24. res := me.mediator.Command(id, cmd)
  25. if res != "OK" {
  26. return errors.New(res)
  27. }
  28. return nil
  29. }

ICloudMediator.go

云中心面向手机app的接口

  1. package mediator
  2. type ICloudMediator interface {
  3. Command(id int, cmd string) string
  4. }

ICloudCenter.go

云中心面向智能设备的注册接口

  1. package mediator
  2. type ICloudCenter interface {
  3. Register(dev ISmartDevice)
  4. }

ISmartDevice.go

智能设备接口

  1. package mediator
  2. type ISmartDevice interface {
  3. ID() int
  4. Command(cmd string) string
  5. }

tMockCloudMediator.go

虚拟的云中心服务类, 面向手机app实现ICloudMediator接口, 面向智能设备实现ICloudCenter接口

  1. package mediator
  2. import "sync"
  3. type tMockCloudMediator struct {
  4. mDevices map[int]ISmartDevice
  5. mRWMutex *sync.RWMutex
  6. }
  7. func newMockCloudMediator() ICloudMediator {
  8. return &tMockCloudMediator{
  9. make(map[int]ISmartDevice),
  10. new(sync.RWMutex),
  11. }
  12. }
  13. func (me *tMockCloudMediator) Register(it ISmartDevice) {
  14. me.mRWMutex.Lock()
  15. defer me.mRWMutex.Unlock()
  16. me.mDevices[it.ID()] = it
  17. }
  18. func (me *tMockCloudMediator) Command(id int, cmd string) string {
  19. me.mRWMutex.RLock()
  20. defer me.mRWMutex.RUnlock()
  21. it,ok := me.mDevices[id]
  22. if !ok {
  23. return "device not found"
  24. }
  25. return it.Command(cmd)
  26. }
  27. var DefaultCloudMediator = newMockCloudMediator()
  28. var DefaultCloudCenter = DefaultCloudMediator.(ICloudCenter)

tMockSmartLight.go

虚拟的智能灯设备, 实现ISmartDevice接口

  1. package mediator
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. type tMockSmartLight struct {
  8. id int
  9. }
  10. func NewMockSmartLight(id int) ISmartDevice {
  11. return &tMockSmartLight{
  12. id,
  13. }
  14. }
  15. func (me *tMockSmartLight) ID() int {
  16. return me.id
  17. }
  18. func (me *tMockSmartLight) Command(cmd string) string {
  19. if cmd == "light open" {
  20. e := me.open()
  21. if e != nil {
  22. return e.Error()
  23. }
  24. } else if cmd == "light close" {
  25. e := me.close()
  26. if e != nil {
  27. return e.Error()
  28. }
  29. } else if strings.HasPrefix(cmd, "light switch_mode") {
  30. args := strings.Split(cmd, " ")
  31. if len(args) != 3 {
  32. return "invalid switch command"
  33. }
  34. n, e := strconv.Atoi(args[2])
  35. if e != nil {
  36. return "invalid mode number"
  37. }
  38. e = me.switchMode(n)
  39. if e != nil {
  40. return e.Error()
  41. }
  42. } else {
  43. return "unrecognized command"
  44. }
  45. return "OK"
  46. }
  47. func (me *tMockSmartLight) open() error {
  48. fmt.Printf("tMockSmartLight.open, id=%v\n", me.id)
  49. return nil
  50. }
  51. func (me *tMockSmartLight) close() error {
  52. fmt.Printf("tMockSmartLight.close, id=%v\n", me.id)
  53. return nil
  54. }
  55. func (me *tMockSmartLight) switchMode(mode int) error {
  56. fmt.Printf("tMockSmartLight.switchMode, id=%v, mode=%v\n", me.id, mode)
  57. return nil
  58. }

中介者模式小结

  1. 中介者模式的优点
  2. 1)减少类间依赖,将多对多依赖转化成一对多,降低了类间耦合。
  3. 2)类间各司其职,符合迪米特法则。
  4. 中介者模式的缺点
  5. 中介者模式将原本多个对象直接的相互依赖变成了中介者和多个同事类的依赖关系。
  6. 当同事类越多时,中介者就会越臃肿,变得复杂且难以维护。
  7. (摘自 谭勇德 <<设计模式就该这样学>>)

(end)