Widget oPooledWidget = (Widget)oObjectPool.borrowObject();
Widget oInjectedWidget = oAppContext.getBeans("widget");
Widget oFactoryWidget = oWidgetFactory.createWidget();
Many different ways exist to instantiate classes without the new
operator and a constructor, and I'm looking for the generally-accepted use cases/scenarios for when to choose one over the other.
Obviously it is not appropriate to pool objects in certain circumstances, such as when you either have no idea how big the pool could get, or when you know the pool would be huge.
But what is an appropriate scenario that calls for pooling? When does pooling offer benefits over dependency injection or factory classes?
Similarly, when would one want to choose using a factory class over dependency injection, and vice versa?
Dependency injection came from a time when code had gazillion of Factories. So, DI is a convinient replacement for Factories. You can call DI context as a universal Factory. Also, object pool can be a bean defined in DI context. Though object pool implements an interface that application code must use in order to keep the pool consistent. Objects retrieved from the pool have different lifecycle compared to DI context beans:
pool = appContext.getBean("connectionPool");
conn = pool.get();
try {
// .. do stuff
} finally {
conn.close();
// or
pool.release(conn);
}