github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/go4java/runner/runner.go (about) 1 // Package runner provides a Runner type that is used to define both RunCounter 2 // and EmbeddedRunCounter to show examples of how to use composition in Go. 3 package runner 4 5 import "fmt" 6 7 // A Task is a simple task that prints a message when run. 8 type Task struct{ Msg string } 9 10 func (t Task) Run() { 11 fmt.Println("running", t.Msg) 12 } 13 14 // END_TASK OMIT 15 16 // A Runner provides a way of running tasks. 17 type Runner struct{ name string } 18 19 func (r *Runner) Name() string { return r.name } 20 21 func (r *Runner) Run(t Task) { 22 t.Run() 23 } 24 25 func (r *Runner) RunAll(ts []Task) { 26 for _, t := range ts { 27 r.Run(t) 28 } 29 } 30 31 // END_RUNNER OMIT 32 33 // A RunCounter is a Runner that keeps a counter of the run tasks. 34 type RunCounter struct { 35 runner Runner // HL 36 count int 37 } 38 39 func NewRunCounter(name string) *RunCounter { 40 return &RunCounter{runner: Runner{name}} 41 } 42 43 func (r *RunCounter) Run(t Task) { 44 r.count++ 45 r.runner.Run(t) // HL 46 } 47 48 func (r *RunCounter) RunAll(ts []Task) { 49 r.count += len(ts) 50 r.runner.RunAll(ts) // HL 51 } 52 53 func (r *RunCounter) Count() int { return r.count } 54 55 func (r *RunCounter) Name() string { return r.runner.Name() }