Skip to content

Instantly share code, notes, and snippets.

@fcamel
Last active April 4, 2022 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcamel/12ca99e1816ced2311d50131c809b17b to your computer and use it in GitHub Desktop.
Save fcamel/12ca99e1816ced2311d50131c809b17b to your computer and use it in GitHub Desktop.
active object pattern in go
package main
import "fmt"
type One int
type Ten int
type work struct {
object interface{}
result chan error
}
type ActiveObject struct {
workChan chan work
sum int
}
func NewActiveObject() *ActiveObject {
a := ActiveObject{make(chan work, 32), 0}
go a.main()
return &a
}
func (a *ActiveObject) main() {
for {
select {
case w := <-a.workChan:
switch v := w.object.(type) {
case One:
a.sum += int(v)
w.result <- nil
case Ten:
a.sum += int(v) * 10
w.result <- nil
case chan int:
v <- a.sum
}
}
}
}
func (a *ActiveObject) AddOne(one One) chan error {
ch := make(chan error, 1)
a.workChan <- work{one, ch}
return ch
}
func (a *ActiveObject) AddTen(ten Ten) chan error {
ch := make(chan error, 1)
a.workChan <- work{ten, ch}
return ch
}
func (a *ActiveObject) GetSum() chan int {
ch := make(chan int, 1)
a.workChan <- work{ch, nil}
return ch
}
func main() {
a := NewActiveObject()
one := One(1)
ch := a.AddOne(one)
ten := Ten(2)
ch2 := a.AddTen(ten)
ch3 := a.GetSum()
err := <-ch
fmt.Println(err)
err = <-ch2
fmt.Println(err)
sum := <-ch3
fmt.Println(sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment