Skip to content

Instantly share code, notes, and snippets.

@Tomotoes
Created August 18, 2019 08:48
Show Gist options
  • Save Tomotoes/12500c03c99775bbacc5ad2c84830115 to your computer and use it in GitHub Desktop.
Save Tomotoes/12500c03c99775bbacc5ad2c84830115 to your computer and use it in GitHub Desktop.
Design Pattern - Active Object
package main
import "fmt"
type MethodRequest int
const (
Incr MethodRequest = iota
Decr
)
type Service struct {
queue chan MethodRequest
v int
}
func (s *Service) Incr() {
s.queue <- Incr
}
func (s *Service) Decr() {
s.queue <- Decr
}
func (s *Service) schedule() {
for r := range s.queue {
if r == Incr {
s.v++
} else if r == Decr {
s.v--
}
}
}
func New(buffer int) *Service {
s := &Service{
queue: make(chan MethodRequest, buffer),
}
go s.schedule()
return s
}
func main() {
s := New(0)
s.Incr()
s.Decr()
s.Decr()
fmt.Println(s.v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment