Rule Definition
On large software applications, the number of factory classes can become quite large. There is lot of code duplication because constructors are private and the usage of static methods and variables make the class not extendable. Thus very singleton must re-implement the same basic structure.
Spring provides a core factory pattern, which eliminates the need to manually program factory objects (usually realized as singletons). It allows you to decouple the configuration and specification of dependencies from your actual program logic. You will remove the need of your own glue code and gain a much more robust factory implementation with better error handling and fully de-coupled configuration mechanism
It will also avoid to fall into the classic double-checked locking issue where you can easily have more than one singleton instance when invoked into a multi-threaded application.
Remediation
Define a factory or singleton using Spring framework
Violation Code Sample
-----> MyInterface.java
interface MyInterface {
public String getAName();
}
-----> MyConcrete.java
class MyConcrete extends MyInterface {
public MyConcrete() {
...
}
public String getAName() {
...
}
}
-----> MyFactory.java
// VIOLATION: the factory pattern is detected
class MyFactory {
private MyFactory() {
...
}
public static MyInterface getMyInterface () {
...
}
}
----> Java Client code
MyInterface theInterface = MyFactory.getMyInterface ();
String name = theInterface.getAName();
Fixed Code Sample
----> Spring XML file
// FIXED with Spring
<beans>
<bean name="theInterface"
class="MyConcrete">
</beans>
----> Java Client code
InputStream is = new FileInputStream("spring_beans.xml");
BeanFactory factory = new XmlBeanFactory(is);
MyInterface theInterface = (MyInterface) factory.getBean("theInterface");
String name = theInterface.getAName();
Reference
http://www.devx.com/Java/Article/21665/1763/page/2
http://www.javapassion.com/j2ee/springhelloworld.pdf
http://wiki.java.net/bin/view/Javapedia/Singleton
http://java.sun.com/developer/JDCTechTips/2006/tt0113.html#1
http://static.springframework.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes-singleton
Related Technologies
JEE
Technical Criterion
Complexity - OO Inheritance and Polymorphism
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.