Last one from the family of creational patterns is Object Pool. The main
purpose of object pool and why designers choose to incorporate to the software
is a performance boost. Construction and destruction of object can become very
expensive operation in some cases (especially if it occurs very often).
Constant building and throwing away instances may significantly slow down your
application. Object Pool pattern offers a solution to this problem. Object pool
is a managed set of reusable objects. Clients then “check out” objects from the
pool return them back when they don’t need them any more. But it’s not that
easy as it sounds. The manager of the pool has to deal with various problems.
What happens if the pool is empty and a client asks for an object? Some
implementations work with growing pool of objects. That means if there’s no
object available at the time of the request the pool manager creates one more.
The manager can also destroy objects periodically when they’re not used. But
what was the initial goal? Performance boost? Well, with this amount of
overhead it might not be as fast. Another solution to the problem is simply to
decline a client’s request if the pool is empty. This also slows down your
system, because clients needs to do things right now and not wait for someone
else to free up resources.
When the reservation expires? The other problem is dealing with errors.
Every client must explicitly free up the resource when he’s done. But
programmers are also only humans (well, in most cases) and there will be errors
and your pool can easily become a hole full of zombies. So you might need to
implement an algorithm for detecting and freeing expired reservations on
resources in order to make stuff work properly.
Synchronization in multi-threaded applications Multi-threading brings
into the game a whole other aspect. Two processes asking for resources at the
same time. Some synchronization tools might be necessary as well.
As you can see, there are some serious drawbacks in this pattern. It’s a huge
amount of work in the first place, if you decide to implement all the above.
You need to consider every aspect very carefully before you implement the
object pool and evaluate whether it really is, what you need.
The resource manager can be implemented many ways. Static class or singleton
will work. I personally chose singleton. Here is my implementation of object
Download the fully working example from