Design Pattern Evangelist Blog

Smart pointers about software design

Maintained by Jim Humelsine | Table of Contents | RSS Feed | Edit on GitHub

WORK IN PROGRESS – Object Pool Design Pattern

TBD


Introduction

The Gang of Four (GoF) included Flyweight, but cataloged it as a structural design pattern. They may have felt that most interactions with Flyweight returned an existing object rather than creating a new one. But if this were the case, then Singleton should have been a structural design pattern too.

The GoF completely ignored Object Pool as a design pattern, creational, structural or otherwise. I’m not sure why, since I’m sure that the Thread Pools existed during the time of publication.

Mad Men

And there are plenty of real world examples of shared Resource Pools including:

Intent

Flyweight and Object Pool are both about +++ TBD +++

Summary

References

Complete Demo Code

Here’s the entire implementation up to this point as one file. Copy and paste it into a Java environment and execute it. If you don’t have Java, try this Online Java Environment. Play with the implementation.

+++++++++++++++++++++++++++++++++++++

NOTES

I consider it a creational pattern even if the objects are not being created. The client is still acquiring them.

Feels similar to Flyweight structurally, but it’s different. Both involve collections of objects. Flyweight objects are shared. Object Pool objects are not shared.

Object Pools are used when an object is resource intensive. It make take a lot of time to instantiate, or it may be tied to a limited resource.

Even if most haven’t implemented an Object Pool, most have used one. A Thread Pool is an object pool.

Objects need to be returned to the pool otherwise you’ll end up with a drained pool. I don’t think that work references will work. Need a means to release the object. Maybe something like close() might help.

Objects need to be cleaned of any intrinsic state, otherwise, you could end up with a cess pool.

What to do when an object is requested, but the pool is empty?

As for an implementation, consider using a Queue. May need an initialize(arguments) method as well.

Still have to deal with concurrency and state. Memory leaks is a different topic. This pattern will always leak in that objects are added to the pool at start up and they remain as long as the process is running.

Previous: Flyweight/Multiton Design Pattern

Home: Design Pattern Evangelist Blog