Created
April 1, 2022 10:27
-
-
Save xfstart07/994a27307f022259897c86c574ac03fe to your computer and use it in GitHub Desktop.
active object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://colobu.com/2019/07/02/concurrency-design-patterns-active-object/