Prototypes are used where there is a state mantained for each instance (you can use singleton when there is no inner bean state that should differs among instances).
Let's say you want to have an image thumbnailer and you want to create thumbnails of the image in different sizes. But loading an image to a memory can be costly. So you can store a loaded image in a prototype instance.
Code:
class ThumbnailerImpl implements Thumbnailer, ResouceHolder {
void setResource(Resource r) {load image here from the resource}
Resource doThumbnail(int size) {create thumbnail here}
}
class ThumbnailerFactory() {
Thumbnailer createThumbnailer(Resource image) {
ResourceHolder thumbnailer = ctx.getBean("thumbnailerPrototypeBean");
thumbnailer.setResource(image);
return (Thumbnailer) thumbnailer;
}
}
Why do you want the ThumbnailerImpl class be a Spring prototype bean instead of creating its instances using new operator in the ThumbnailFactory? Maybe because you want to inject actual thumbnail algorithm into it or apply Spring AOP on it.