gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/myx/pool/pool.go (about) 1 package pool 2 3 func NewPool() (obj *Pool) { 4 obj = &Pool{} 5 return 6 } 7 8 type Pool struct { 9 items []interface{} 10 count int 11 creator func(...interface{}) interface{} 12 } 13 14 func (p *Pool) SetCreator(c func(...interface{}) interface{}) { 15 p.creator = c 16 } 17 18 func (p *Pool) Dispose() { 19 p.items = nil 20 } 21 func (p *Pool) Count() int { 22 return p.count 23 } 24 25 func (p *Pool) GetItem() (r interface{}) { 26 items := p.items 27 p.count++ 28 l := len(items) 29 if l == 0 { 30 return 31 } else { 32 r = items[l-1] 33 items[l-1] = nil 34 p.items = items[:l-1] 35 } 36 37 return 38 } 39 40 func (p *Pool) GetOrNewItem(args ...interface{}) (r interface{}) { 41 items := p.items 42 p.count++ 43 l := len(items) 44 if l == 0 { 45 if p.creator == nil { 46 return 47 } 48 r = p.creator(args...) 49 } else { 50 r = items[l-1] 51 items[l-1] = nil 52 p.items = items[:l-1] 53 } 54 55 return 56 } 57 58 func (p *Pool) PutItem(r interface{}) { 59 items := p.items 60 p.items = append(items, r) 61 // 62 p.count-- 63 }