From d45a49a78b5797e14f9050f2a4853db39438be7b Mon Sep 17 00:00:00 2001 From: Edward Date: Tue, 5 May 2020 22:59:18 +0800 Subject: [PATCH] finish object pool pattern --- creation/04_object_pool/obejct_poo.go | 16 ++++++++++++---- creation/04_object_pool/object_pool_test.go | 16 +++++++++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/creation/04_object_pool/obejct_poo.go b/creation/04_object_pool/obejct_poo.go index 15c9dc8..19a2529 100644 --- a/creation/04_object_pool/obejct_poo.go +++ b/creation/04_object_pool/obejct_poo.go @@ -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) } diff --git a/creation/04_object_pool/object_pool_test.go b/creation/04_object_pool/object_pool_test.go index 2e7baa6..177c414 100644 --- a/creation/04_object_pool/object_pool_test.go +++ b/creation/04_object_pool/object_pool_test.go @@ -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 } }