网站建设数据库配置,免费网站建设itcask,网站套模板什么意思,wordpress大前端主题中介者模式
中介者模式封装对象之间互交#xff0c;使依赖变的简单#xff0c;并且使复杂互交简单化#xff0c;封装在中介者中。
例子中的中介者使用单例模式生成中介者。
中介者的change使用switch判断类型。
mediator.go
package mediatorimport (fmt使依赖变的简单并且使复杂互交简单化封装在中介者中。
例子中的中介者使用单例模式生成中介者。
中介者的change使用switch判断类型。
mediator.go
package mediatorimport (fmtstrings
)type CDDriver struct {Data string
}func (c *CDDriver) ReadData() {c.Data music,imagefmt.Printf(CDDriver: reading data %s\n, c.Data)GetMediatorInstance().changed(c)
}type CPU struct {Video stringSound string
}func (c *CPU) Process(data string) {sp : strings.Split(data, ,)c.Sound sp[0]c.Video sp[1]fmt.Printf(CPU: split data with Sound %s, Video %s\n, c.Sound, c.Video)GetMediatorInstance().changed(c)
}type VideoCard struct {Data string
}func (v *VideoCard) Display(data string) {v.Data datafmt.Printf(VideoCard: display %s\n, v.Data)GetMediatorInstance().changed(v)
}type SoundCard struct {Data string
}func (s *SoundCard) Play(data string) {s.Data datafmt.Printf(SoundCard: play %s\n, s.Data)GetMediatorInstance().changed(s)
}type Mediator struct {CD *CDDriverCPU *CPUVideo *VideoCardSound *SoundCard
}var mediator *Mediatorfunc GetMediatorInstance() *Mediator {if mediator nil {mediator Mediator{}}return mediator
}func (m *Mediator) changed(i interface{}) {switch inst : i.(type) {case *CDDriver:m.CPU.Process(inst.Data)case *CPU:m.Sound.Play(inst.Sound)m.Video.Display(inst.Video)}
}mediator_test.go
package mediatorimport testingfunc TestMediator(t *testing.T) {mediator : GetMediatorInstance()mediator.CD CDDriver{}mediator.CPU CPU{}mediator.Video VideoCard{}mediator.Sound SoundCard{}//Tigglemediator.CD.ReadData()if mediator.CD.Data ! music,image {t.Fatalf(CD unexpect data %s, mediator.CD.Data)}if mediator.CPU.Sound ! music {t.Fatalf(CPU unexpect sound data %s, mediator.CPU.Sound)}if mediator.CPU.Video ! image {t.Fatalf(CPU unexpect video data %s, mediator.CPU.Video)}if mediator.Video.Data ! image {t.Fatalf(VidoeCard unexpect data %s, mediator.Video.Data)}if mediator.Sound.Data ! music {t.Fatalf(SoundCard unexpect data %s, mediator.Sound.Data)}
}