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 package objectpool
import (
"fmt"
"strconv"
)
type doctor struct { type doctor struct {
name string name string
kind int //科室 kind int //科室,1内科2外科
} }
type pool chan *doctor type pool chan *doctor
@ -11,13 +16,16 @@ func newPool(total int) pool {
p := make(pool, total) p := make(pool, total)
for i := 0; i < total; i++ { for i := 0; i < total; i++ {
p <- new(doctor)
dc := new(doctor)
dc.name = "doctor: " + strconv.Itoa(i)
p <- dc
} }
return p return p
} }
//surgery //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 package objectpool
import ( import (
"fmt"
"testing" "testing"
) )
func TestObjectPool(t *testing.T) { 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 { select {
case obj := <-p: case obj := <-p:
obj.surgery( /*...*/ ) obj.surgery("lily")
p <- obj p <- obj
default: default:
// No more objects left — retry later or fail // No more objects left — retry later or fail
fmt.Println("No more objects left, this moment")
return return
} }
} }