Difference between adding instance and caching

87 Views Asked by At

What's the difference between those two codes? Both of them produce the same result.

With caching:

DefaultPicoContainer cachingContainer = new DefaultPicoContainer(new OptInCaching().wrap(new ConstructorInjection()));

cachingContainer.as(Characteristics.CACHE).addComponent(Cookie.class);

Cookie cookie1 = (Cookie)cachingContainer.getComponent(Cookie.class);
Cookie cookie2 = (Cookie)cachingContainer.getComponent(Cookie.class);

assert(cookie1 == cookie2); // Same instance: OK

Adding an instance:

DefaultPicoContainer instanceContainer = new DefaultPicoContainer(new ConstructorInjection());

instanceContainer.addComponent(Cookie.class, new Cookie());

Cookie cookie3 = (Cookie)instanceContainer.getComponent(Cookie.class);
Cookie cookie4 = (Cookie)instanceContainer.getComponent(Cookie.class);

assert(cookie3 == cookie4); // Same instance: OK
1

There are 1 best solutions below

0
On

In first case you delegate object instantiation to the container, and that managed instance is cached. In second case you store ready instance in the container as Cookie type.

Managed components (first case) will have their dependencies autowired, also they may have lifecycle events etc. In the most cases you should delegate instantiation to the container.