Wednesday, May 4, 2011

proton

I decided to go ahead and throw proton up on BitBucket. What is it?

Proton is an implementation of the common Prototype Design Pattern. What this boils down to is a single interface Prototype for creating copies of a pre-configured instance. An implementation can do whatever it wants to create prototypes, but once you pass the Prototype implementation off to clients it should do a good job of consistently returning usable copies from the newInstance method.

Why is this useful? Originally the Prototype pattern was used to implement a kind of object pooling because creating new objects is expensive. But the pattern is actually much more useful and powerful than this; the Prototype pattern can be used anytime one object needs to (continually) create instances of another object the creator either does not or should not have enough information to actually do the creation on its own. This tends to happen when objects have a 'structural' relationship rather than a functional relationship. A needs to create B and offer it on demand to C but A generally never invokes methods on B and doesn't know much about it at all.

In my particular case I was using JAXRS sub-resources and needed to have Root Resources create child Resources. I was also using Spring and wanted my child resources to get dependency injection and AOP and all that good stuff. To work around this I created a SpringPrototype that will go to the ApplicationContext and instantiate my sub-resources. (This only works of course if your scope="prototype" for your sub-resource prototypes.)

The next question was how to have the root resources get their hands on Prototypes for the sub-resources. I could've just done this using plain ol' spring xml as prototypes are just plain beans at the end of the day but I saw an opportunity to save some time by creating a custom BeanPostProcessor that would automagically inject prototypes into those resource classes that needed it after Spring has done all of its normal DI.

No comments:

Post a Comment