Go設計模式之中介者模式講解和代碼示例
更新時間:2023年06月29日 08:23:49 作者:demo007x
中介者是一種行為設計模式,讓程序組件通過特殊的中介者對象進行間接溝通,達到減少組件之間依賴關系的目的,因此本文就給大家詳細介紹一下Go中介者模式,需要的朋友可以參考下
Go 中介者模式講解和代碼示例
中介者能使得程序更易于修改和擴展, 而且能更方便地對獨立的組件進行復用, 因為它們不再依賴于很多其他的類。
概念示例
中介者模式的一個絕佳例子就是火車站交通系統。 兩列火車互相之間從來不會就站臺的空閑狀態(tài)進行通信。 stationManager
車站經理可充當中介者, 讓平臺僅可由一列入場火車使用, 而將其他火車放入隊列中等待。 離場火車會向車站發(fā)送通知, 便于隊列中的下一列火車進站。
train.go: 組件
package main type Train interface { arrive() depart() permitArrival() }
passengerTrain.go: 具體組件
package main import "fmt" type PassengerTrain struct { mediator Mediator } // 火車??? func (pt *PassengerTrain) arrive() { if !pt.mediator.canArrive(pt) { fmt.Println("PassengerTrain: Arrival blocked, waiting") return } fmt.Println("PassengerTrain: arrived") } // 獲取離開 func (pt *PassengerTrain) depart() { fmt.Println("PassengerTrain: leaving") pt.mediator.notifyAboutDeparture() } func (pt *PassengerTrain) permitArrival() { fmt.Println("PassengerTrain: Arrival permitted, arriving") pt.arrive() }
freightTrain.go: 具體組件
package main import "fmt" type FreightTrain struct { mediator Mediator } func (g *FreightTrain) arrive() { if !g.mediator.canArrive(g) { fmt.Println("FreightTrain: Arrival blocked, waiting") return } fmt.Println("FreightTrain: arrived") } func (g *FreightTrain) depart() { fmt.Println("FreightTrain: leaving") g.mediator.notifyAboutDeparture() } func (g *FreightTrain) permitArrival() { fmt.Println("FreightTrain: Arrival permitted") g.arrive() }
mediator.go: 中介者接口
package main type Mediator interface { canArrive(Train) bool notifyAboutDeparture() }
stationManager.go: 具體中介者
package main type StationManager struct { isPlatformFree bool trainQueue []Train } func newStationManager() *StationManager { return &StationManager{ isPlatformFree: true, } } func (s *StationManager) canArrive(t Train) bool { if s.isPlatformFree { s.isPlatformFree = false return true } s.trainQueue = append(s.trainQueue, t) return false } func (s *StationManager) notifyAboutDeparture() { if !s.isPlatformFree { s.isPlatformFree = true } if len(s.trainQueue) > 0 { firstTrainInQueue := s.trainQueue[0] s.trainQueue = s.trainQueue[1:] firstTrainInQueue.permitArrival() } }
main.go: 客戶端代碼
package main func main() { stationManager := newStationManager() passengerTrain := &PassengerTrain{ mediator: stationManager, } freightTrain := &FreightTrain{ mediator: stationManager, } passengerTrain.arrive() freightTrain.arrive() passengerTrain.depart() }
到此這篇關于Go設計模式之中介者模式講解和代碼示例的文章就介紹到這了,更多相關Go 中介者模式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
golang?使用sort.slice包實現對象list排序
這篇文章主要介紹了golang?使用sort.slice包實現對象list排序,對比sort跟slice兩種排序的使用方式區(qū)別展開內容,需要的小伙伴可以參考一下2022-03-03golang gin 框架 異步同步 goroutine 并發(fā)操作
這篇文章主要介紹了golang gin 框架 異步同步 goroutine 并發(fā)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12