Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import "fmt"
- // Task is the task
- type Task struct {
- task string
- payload string
- }
- // Worker interface
- type Worker interface {
- Work(Task) (bool, error)
- }
- // WorkerA do something
- type WorkerA struct{}
- // Work specific for WorkerA
- func (WorkerA) Work(t Task) (bool, error) {
- return true, nil
- }
- func (WorkerA) String() string {
- return "WorkerA"
- }
- // WorkerB do something else
- type WorkerB struct{}
- // Work specific for WorkerB
- func (WorkerB) Work(t Task) (bool, error) {
- return false, nil
- }
- func (WorkerB) String() string {
- return "WorkerB"
- }
- // Manager for all workers type
- type Manager struct {
- worker Worker
- tasks []Task
- workers []Worker
- }
- // RunWorker of defined type
- func (m *Manager) RunWorker() {
- // Make worker of needed type
- worker := m.worker
- // Append worker of needed type
- m.workers = append(m.workers, worker)
- }
- func main() {
- // Constructor with worker type definition!!!
- manager := Manager{worker: new(WorkerA)}
- manager.RunWorker()
- manager.RunWorker()
- fmt.Println(manager.workers)
- anotherManager := Manager{worker: new(WorkerB)}
- anotherManager.RunWorker()
- anotherManager.RunWorker()
- anotherManager.RunWorker()
- fmt.Println(anotherManager.workers)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement