|
|||||
|
|||||
Singleton Compared
Pico, Spring and Nuts all provide declarative singleton support. Pico provides a CachingComponentAdapter for decorating a ComponentAdapter as a singleton; Yan has a singleton() method that internally creates a singleton decorator. Basically Pico and Yan share the same idea on how singleton is implemented. Spring is slightly different. Singleton semantics is implemented centrally by the BeanFactory, rather than individual beans. This approach taken by Spring lacks some flexibility compared to Pico/Yan's approach. Pico and Yan also support scoped singleton, where cached instance is not simply stored in a member variable. For example, Yan allows the instance to be stored in a thread local object, which enables one instance per thread. Let's see a more concrete example:
The Java pseudo code is: private A singleton; private A getSingletonInstance(){ if(singleton==null){ this.singleton = new A(); } return singleton; } public synchronized A getInstance(){ final A instance = getSingletonInstance(); instance.setB(new B()); } Bizarre requirement, you may say. Well, the following statements are copied from Spring reference:
Honestly, I like neither of the solutions. Forgoing IOC isn't good and relying on bytecode generation sounds like a big deal to me. As we just saw, this logic can be easily expressed in Java, why does it have to be so awkward in an IOC container? I'll not show the Java code using Pico or Yan. It's not so fair to compare xml with a full blown programming language like Java after all. In Nuts, this is what we will do to implement this requirement: <ctor id="getSingletonInstance" class="A" args="" singleton="true"/> <bean id="getInstance" component="$getSingletonInstance" singleton="false" synchronized="true"> <prop key="b"> <ctor class="B" args=""/> </prop> </bean> We keep "getSingletonInstance" as singleton so that we will always get the same instance. Slightly refactored, we can hide the "getSingletonInstance" as a nested sub-element: <bean id="getInstance" component="$getSingletonInstance" singleton="false" synchronized="true"> <ctor id="getSingletonInstance" class="A" args="" singleton="true"/> <prop key="b"> <ctor class="B" args=""/> </prop> </bean> Either way, it is a straight-forward translation of the Java pseudo code. |
|||||
|
Copyright 2003-2006 - The Codehaus. All rights reserved unless otherwise noted.
Powered by Atlassian Confluence
|
|||||