mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-21 19:36:03 +03:00
finish object pool pattern
This commit is contained in:
parent
6a72ca4b8e
commit
d45a49a78b
@ -1,8 +1,13 @@
|
||||
package objectpool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type doctor struct {
|
||||
name string
|
||||
kind int //科室
|
||||
kind int //科室,1内科,2外科
|
||||
}
|
||||
|
||||
type pool chan *doctor
|
||||
@ -11,13 +16,16 @@ func newPool(total int) pool {
|
||||
p := make(pool, total)
|
||||
|
||||
for i := 0; i < total; i++ {
|
||||
p <- new(doctor)
|
||||
|
||||
dc := new(doctor)
|
||||
dc.name = "doctor: " + strconv.Itoa(i)
|
||||
p <- dc
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
//surgery
|
||||
func (d doctor) surgery() {
|
||||
|
||||
func (d doctor) surgery(someone string) {
|
||||
fmt.Println("doctor:", d.name, "do surgery for", someone)
|
||||
}
|
||||
|
@ -1,20 +1,30 @@
|
||||
package objectpool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestObjectPool(t *testing.T) {
|
||||
|
||||
p := newPool(2)
|
||||
p := newPool(3)
|
||||
|
||||
doc1 := <-p
|
||||
doc1.surgery("tom")
|
||||
|
||||
doc2 := <-p
|
||||
doc2.surgery("rose")
|
||||
|
||||
doc3 := <-p
|
||||
doc3.surgery("kate")
|
||||
|
||||
select {
|
||||
case obj := <-p:
|
||||
obj.surgery( /*...*/ )
|
||||
|
||||
obj.surgery("lily")
|
||||
p <- obj
|
||||
default:
|
||||
// No more objects left — retry later or fail
|
||||
fmt.Println("No more objects left, this moment")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user