Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.26 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. // Task is the task
  6. type Task struct {
  7.     task    string
  8.     payload string
  9. }
  10.  
  11. // Worker interface
  12. type Worker interface {
  13.     Work(Task) (bool, error)
  14. }
  15.  
  16. // WorkerA do something
  17. type WorkerA struct{}
  18.  
  19. // Work specific for WorkerA
  20. func (WorkerA) Work(t Task) (bool, error) {
  21.     return true, nil
  22. }
  23.  
  24. func (WorkerA) String() string {
  25.     return "WorkerA"
  26. }
  27.  
  28. // WorkerB do something else
  29. type WorkerB struct{}
  30.  
  31. // Work specific for WorkerB
  32. func (WorkerB) Work(t Task) (bool, error) {
  33.     return false, nil
  34. }
  35.  
  36. func (WorkerB) String() string {
  37.     return "WorkerB"
  38. }
  39.  
  40. // Manager for all workers type
  41. type Manager struct {
  42.     worker  Worker
  43.     tasks   []Task
  44.     workers []Worker
  45. }
  46.  
  47. // RunWorker of defined type
  48. func (m *Manager) RunWorker() {
  49.     // Make worker of needed type
  50.     worker := m.worker
  51.     // Append worker of needed type
  52.     m.workers = append(m.workers, worker)
  53. }
  54.  
  55. func main() {
  56.     // Constructor with worker type definition!!!
  57.     manager := Manager{worker: new(WorkerA)}
  58.  
  59.     manager.RunWorker()
  60.     manager.RunWorker()
  61.  
  62.     fmt.Println(manager.workers)
  63.  
  64.     anotherManager := Manager{worker: new(WorkerB)}
  65.  
  66.     anotherManager.RunWorker()
  67.     anotherManager.RunWorker()
  68.     anotherManager.RunWorker()
  69.  
  70.     fmt.Println(anotherManager.workers)
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement