Skip to content

Instantly share code, notes, and snippets.

@arnobroekhof
Created April 12, 2019 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save arnobroekhof/a9ebea5a72fb00ebdb3ceb191b6f0019 to your computer and use it in GitHub Desktop.
Save arnobroekhof/a9ebea5a72fb00ebdb3ceb191b6f0019 to your computer and use it in GitHub Desktop.
starbucks.go --> example
package main
import (
"fmt"
"time"
)
type Barista struct {
name string
orders chan string // channel of orders
drinks chan string // channel of drinks
}
var drinks = map[string]int{
"Flat white": 2,
"Filter": 4,
}
func (b Barista) makeDrink(name string) {
fmt.Println(b.name, "making", name)
time.Sleep(time.Second * time.Duration(drinks[name]))
}
func (b Barista) waitForOrders() {
for {
fmt.Println(b.name, "waiting for orders")
drink := <-b.orders
b.makeDrink(drink)
b.drinks <- drink
}
}
func NewBarista(name string, orders chan string, drinks chan string) Barista {
b := Barista{name, orders, drinks}
go b.waitForOrders()
return b
}
type Customer struct {
name string
orders chan string
drinks chan string
}
func (c Customer) collectDrink() {
fmt.Println(c.name, "waiting to collect drink")
drink := <-c.drinks
fmt.Println(c.name, "collected", drink)
}
func (c Customer) order(drink string) {
fmt.Println(c.name, "ordered a", drink)
c.orders <- drink
c.collectDrink()
}
func NewCustomer(name string, orders chan string, drinks chan string) Customer {
c := Customer{name, orders, drinks}
return c
}
func main() {
orders := make(chan string)
drinks := make(chan string)
NewBarista("Bas", orders, drinks)
NewBarista("Martin", orders, drinks)
c1 := NewCustomer("Arno", orders, drinks)
c2 := NewCustomer("David", orders, drinks)
c1.order("Filter")
c2.order("Flat white")
time.Sleep(time.Second * 10)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment