1
0
mirror of https://github.com/tmrts/go-patterns.git synced 2024-11-28 07:56:06 +03:00
go-patterns/creational/object-pool.md

49 lines
923 B
Markdown
Raw Normal View History

# Object Pool Pattern
The object pool creational design pattern is used to prepare and keep multiple
instances according to the demand expectation.
## Implementation
```go
package pool
type Pool chan *Object
func New(total int) *Pool {
2017-01-07 21:13:23 +03:00
p := make(Pool, total)
for i := 0; i < total; i++ {
p <- new(Object)
}
2017-01-07 21:13:23 +03:00
return &p
}
```
## Usage
Given below is a simple lifecycle example on an object pool.
```go
p := pool.New(2)
select {
case obj := <-p:
obj.Do( /*...*/ )
p <- obj
default:
2017-01-07 21:13:23 +03:00
// No more objects left — retry later or fail
return
}
```
## Rules of Thumb
- Object pool pattern is useful in cases where object initialization is more
expensive than the object maintenance.
- If there are spikes in demand as opposed to a steady demand, the maintenance
overhead might overweigh the benefits of an object pool.
2017-01-07 21:13:23 +03:00
- It has positive effects on performance due to objects being initialized beforehand.