When you need to have one and one only instance of a class in your project, you will probably need to apply the Singleton Software Pattern. With this, there will always be just one instance of the Singleton in your project. This code is an example of Singleton, with test included:
ClassicSingleton.java:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
SingletonTestCase.java:
import org.apache.log4j.Logger;
import junit.framework.Assert;
import junit.framework.TestCase;
public class SingletonTest extends TestCase {
private ClassicSingleton sone = null, stwo = null;
private static Logger logger = Logger.getRootLogger();
public SingletonTest(String name) {
super(name);
}
public void setUp() {
logger.info("getting singleton...");
sone = ClassicSingleton.getInstance();
logger.info("...got singleton: " + sone);
logger.info("getting singleton...");
stwo = ClassicSingleton.getInstance();
logger.info("...got singleton: " + stwo);
}
public void testUnique() {
logger.info("checking singletons for equality");
Assert.assertEquals(true, sone == stwo);
}
}
Results:
Buildfile: build.xml
init:
[echo] Build 20030414 (14-04-2003 03:08)
compile:
run-test-text:
[java] .INFO main: getting singleton...
[java] INFO main: created singleton: Singleton@e86f41
[java] INFO main: ...got singleton: Singleton@e86f41
[java] INFO main: getting singleton...
[java] INFO main: ...got singleton: Singleton@e86f41
[java] INFO main: checking singletons for equality
[java] Time: 0.032
[java] OK (1 test)
As you can see in the results, the two Singletons used are giving the same memory reference; Singleton@e86f41
. Therefore, they are the same object, which is the desired behaviour.
Hope it helps,
Clemencio Morales Lucas.