行为型 中介模式

为什么需要中介模式

中介模式的引入可以想象航空管制,本来每一架飞机都要和其他飞机进行通信联系,情况很多,实现复杂,然而引入中央控制塔台可以缓解这种情况。所有飞机都和塔台通信来降低每架飞机的通信复杂度。

不过相应的,塔台的通信就比较复杂了。

实现

实际操作的对象(飞机),通过调用mediator的对象来进行交互。

go.mod

module mediator

go 1.13

mediator.go

package mediator

type Aircraft interface {
	Connect(mediator *Mediator)
}

type Mediator struct{}

func (m *Mediator) canLand(aircraft Aircraft) bool {
	switch aircraft.(type) {
	case *PlaneA:
		return true
	case *PlaneB:
		return false
	}
	return false
}

type PlaneA struct {
	mediator *Mediator
}

func (p *PlaneA) Connect(mediator *Mediator) {
	p.mediator = mediator
}

func (p *PlaneA) Land() string {
	// need to pass current object to mediator
	if p.mediator.canLand(p) {
		return "Plane A is landing"
	}
	return "Plane A cannot land"
}

type PlaneB struct {
	mediator *Mediator
}

func (p *PlaneB) Connect(mediator *Mediator) {
	p.mediator = mediator
}

func (p *PlaneB) Land() string {
	if p.mediator.canLand(p) {
		return "Plane B is landing"
	}

	return "Plane B cannot land"
}

mediator_test.go

package mediator_test

import (
	"mediator"
	"testing"
)

func TestMediator(t *testing.T) {
	m := &mediator.Mediator{}
	planeA := &mediator.PlaneA{}
	planeB := &mediator.PlaneB{}
	planeA.Connect(m)
	planeB.Connect(m)
	if planeA.Land() != "Plane A is landing" {
		t.Fatal("Mediator does not handle Plane A correctly")
	}
	if planeB.Land() != "Plane B cannot land" {
		t.Fatal("Mediator does not handle Plane B correctly")
	}
}

执行: go test mediator -v

Previous