mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-22 03:46:03 +03:00
finish object pool pattern
This commit is contained in:
parent
6a72ca4b8e
commit
d45a49a78b
@ -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)
|
||||||
}
|
}
|
||||||
|
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user