Skip to content

Instantly share code, notes, and snippets.

@jpukg
Forked from arnobroekhof/starbucks.go
Created February 14, 2022 10:08
Show Gist options
  • Save jpukg/2b558714a9fe8556131245ab20ebd8bf to your computer and use it in GitHub Desktop.
Save jpukg/2b558714a9fe8556131245ab20ebd8bf 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