对象池模式:实例化并维护一组相同类型的对象实例;
Object Pool Pattern
The object pool creational design pattern is used to prepare and keep multiple instances according to the demand expectation.
对象池创建型设计模式是用来准备和保存多个实例根据需求预测。
Implementation1
2
3
4
5
6
7
8
9
10
11
12
13package pool
type Pool chan *Object
func New(total int) *Pool {
p := make(Pool, total)
for i := 0; i < total; i++ {
p <- new(Object)
}
return &p
}
Usage
Given below is a simple lifecycle example on an object pool.
下面是对象池中的简单生命周期示例。
1 | p := pool.New(2) |
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.
It has positive effects on performance due to objects being initialized beforehand.
对象池模式在对象初始化比对象维护更昂贵的情况下非常有用。
如果有需求高峰相对稳定的需求,维护的费用可能会超过一个对象池的好处。
它预先对对象进行初始化,对性能有积极的影响。