Created
December 15, 2023 13:07
-
-
Save Guaderxx/5c491e4466fb2bcfb57b4fb0e6fb1b73 to your computer and use it in GitHub Desktop.
mediator pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type airplane interface { | |
arrive() | |
depart() | |
permitArrival() | |
} | |
type mediator interface { | |
canArrive(airplane) bool | |
notifyAboutDeparture() | |
} | |
type passenger struct { | |
mediator mediator | |
} | |
func (p *passenger) arrive() { | |
if !p.mediator.canArrive(p) { | |
fmt.Println("airplane passenger: Arrival blocked, waiting") | |
return | |
} | |
fmt.Println("airplane passenger: Arrived") | |
} | |
func (p *passenger) depart() { | |
fmt.Println("airplane passenger: Leaving") | |
p.mediator.notifyAboutDeparture() | |
} | |
func (p *passenger) permitArrival() { | |
fmt.Println("airplane passenger: landing permitted, arriving") | |
p.arrive() | |
} | |
type boeing737 struct { | |
mediator mediator | |
} | |
func (b *boeing737) arrive() { | |
if !b.mediator.canArrive(b) { | |
fmt.Println("boeing 737: Landing blocked, waiting") | |
return | |
} | |
fmt.Println("boeing 737: Arrived") | |
} | |
func (b *boeing737) depart() { | |
fmt.Println("boeing 737: Taking off") | |
b.mediator.notifyAboutDeparture() | |
} | |
func (b *boeing737) permitArrival() { | |
fmt.Println("boeing 737: Arrival permitted") | |
b.arrive() | |
} | |
type airportManager struct { | |
isRunwayFree bool | |
airportQueue []airplane | |
} | |
func newStationManager() *airportManager { | |
return &airportManager{ | |
isRunwayFree: true, | |
} | |
} | |
func (a *airportManager) canArrive(p airplane) bool { | |
if a.isRunwayFree { | |
a.isRunwayFree = false | |
return true | |
} | |
a.airportQueue = append(a.airportQueue, p) | |
return false | |
} | |
func (a *airportManager) notifyAboutDeparture() { | |
if !a.isRunwayFree { | |
a.isRunwayFree = true | |
} | |
if len(a.airportQueue) > 0 { | |
firstAirplaneInQueue := a.airportQueue[0] | |
a.airportQueue = a.airportQueue[1:] | |
firstAirplaneInQueue.permitArrival() | |
} | |
} | |
func main() { | |
stationManager := newStationManager() | |
airplanePassenger := &passenger{ | |
mediator: stationManager, | |
} | |
boeing := &boeing737{ | |
mediator: stationManager, | |
} | |
airplanePassenger.arrive() | |
boeing.arrive() | |
airplanePassenger.depart() | |
} | |
// output: | |
// airplane passenger: Arrived | |
// boeing 737: Landing blocked, waiting | |
// airplane passenger: Leaving | |
// boeing 737: Arrival permitted | |
// boeing 737: Arrived |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment