finish object pool pattern

This commit is contained in:
Edward 2020-05-05 22:59:18 +08:00
parent 6a72ca4b8e
commit d45a49a78b
2 changed files with 25 additions and 7 deletions

View File

@ -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)
}

View File

@ -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
}
}