Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package dispatcher
- // Dispatcher is an abstraction to work around cyclic dependencies
- type Dispatcher struct {
- Car CarDispatcher
- Plane PlaneDispatcher
- }
- type CarDispatcher interface {
- // This matches all of the methods of car.Car
- AttachTire(tire interface{}) // This could be typed as "AttachTire(tire *car.Tire)", but that would cause cyclic depedencies
- }
- type PlaneDispatcher interface {
- // This matches all of the methods of plane.Plane
- AttachWing(wing interface{}) // This could be typed as "AttachWing(wing *plane.Wing)", but that would cause cyclic depedencies
- }
- package car
- type Car struct {
- Dispatcher dispatcher.Dispatcher
- }
- type Tire struct {
- rubber int
- tread int
- }
- func (c *Car) AttachTire(tire *Tire) {
- // TODO
- }
- package plane
- type Plane struct {
- Dispatcher dispatcher.Dispatcher
- }
- type Wing struct {
- length int
- foils int
- }
- func (p *Plane) AttachWing(wing *Wing) {
- // TODO
- }
- func (p *Plane) UnloadCarFromPlane(wing *Wing) {
- // I need to access the car package from the plane package
- // I need to access the plane package from the car package
- // Thus, I must call the methods through the dispatcher abstraction
- p.Dispatcher.Car.AttachTire(1) // Oops, I accidently made a type in the argument to the function, but the compiler didn't save me
- }
- package main
- func main() {
- car := &car.Car{}
- plane := &plane.Plane{}
- dispatcher := dispatcher.Dispatcher{}
- dispatcher.Car = car
- dispatcher.Plane = plane
- // Inject dependencies
- car.Dispatcher = dispatcher
- plane.Dispatcher = dispatcher
- // Ok, now do some work
- dispatcher.Plane.UnloadCarFromPlane()
- }
RAW Paste Data