Zamiel

Golang

Jan 17th, 2021 (edited)
930
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package dispatcher
  2.  
  3. // Dispatcher is an abstraction to work around cyclic dependencies
  4. type Dispatcher struct {
  5.     Car   CarDispatcher
  6.     Plane PlaneDispatcher
  7. }
  8.  
  9. type CarDispatcher interface {
  10.     // This matches all of the methods of car.Car
  11.     AttachTire(tire interface{}) // This could be typed as "AttachTire(tire *car.Tire)", but that would cause cyclic depedencies
  12. }
  13.  
  14. type PlaneDispatcher interface {
  15.     // This matches all of the methods of plane.Plane
  16.     AttachWing(wing interface{}) // This could be typed as "AttachWing(wing *plane.Wing)", but that would cause cyclic depedencies
  17. }
  18.  
  19.  
  20.  
  21.  
  22.  
  23. package car
  24.  
  25. type Car struct {
  26.     Dispatcher dispatcher.Dispatcher
  27. }
  28.  
  29. type Tire struct {
  30.     rubber int
  31.     tread int
  32. }
  33.  
  34. func (c *Car) AttachTire(tire *Tire) {
  35.     // TODO
  36. }
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44. package plane
  45.  
  46. type Plane struct {
  47.     Dispatcher dispatcher.Dispatcher
  48. }
  49.  
  50. type Wing struct {
  51.     length int
  52.     foils int
  53. }
  54.  
  55. func (p *Plane) AttachWing(wing *Wing) {
  56.     // TODO
  57. }
  58.  
  59. func (p *Plane) UnloadCarFromPlane(wing *Wing) {
  60.     // I need to access the car package from the plane package
  61.     // I need to access the plane package from the car package
  62.     // Thus, I must call the methods through the dispatcher abstraction
  63.     p.Dispatcher.Car.AttachTire(1) // Oops, I accidently made a type in the argument to the function, but the compiler didn't save me
  64. }
  65.  
  66.  
  67.  
  68.  
  69.  
  70. package main
  71.  
  72. func main() {
  73.     car := &car.Car{}
  74.     plane := &plane.Plane{}
  75.     dispatcher := dispatcher.Dispatcher{}
  76.     dispatcher.Car = car
  77.     dispatcher.Plane = plane
  78.  
  79.     // Inject dependencies
  80.     car.Dispatcher = dispatcher
  81.     plane.Dispatcher = dispatcher
  82.  
  83.     // Ok, now do some work
  84.     dispatcher.Plane.UnloadCarFromPlane()
  85. }
  86.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×