September 22, 2008

Recycling Factory Pattern.

I've been thinking a little about patterns recently as a result of having to interview far too many people in the past week. I've been asking them to tell me about patterns and their relationships.

It's been interesting hearing people talk about the 'evil Singleton' pattern, get muddled over the Factory pattern and refer to the Pool pattern.

The thing that these patterns all have in common is that they provide a mechanism for accessing an object for immediate use,

These patterns all feel like special cases of a more general pattern. More specifically they are implementation patterns of that general pattern. What makes the Singleton evil is not that one instance exists in the JVM but that dependent code knows that a single instance exists in the JVM.

I'm thinking that there is a more general pattern for managing objects that includes a get instance method and a return instance method. The dependent code on this pattern becomes responsible for getting an object, using it and returning it (though a callback could be used too). The dependent code then becomes less aware of whether it is working with an object from a pool, a factory or a singleton and just gets on with using the object. The implementation of the pattern can be switched to any implementation pattern at any time according to need.

This pattern could be called the Recycling Factory Pattern.

On a more general basis this leads me to think that patterns need to be classified into whether they are implementation patterns or something else (can't think of a name yet).