Created
August 18, 2019 08:48
-
-
Save Tomotoes/12500c03c99775bbacc5ad2c84830115 to your computer and use it in GitHub Desktop.
Design Pattern - Active Object
This file contains 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 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