WEB开发网
开发学院WEB开发Jsp Simply Singleton -- part2 By David Geary 阅读

Simply Singleton -- part2 By David Geary

 2008-01-05 18:38:46 来源:WEB开发网   
核心提示:Test singletons Throughout the rest of this article, I use JUnit in concert with log4j to test singleton classes. If you are not familiar with JUnit or log4j, s

Test singletons
Throughout the rest of this article, I use JUnit in concert with log4j to test singleton classes. If you are not familiar with JUnit or log4j, see Resources.

Example 2 lists a JUnit test case that tests Example 1's singleton:

Example 2. A singleton test case

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);
  }
}

Example 2's test case invokes ClassicSingleton.getInstance() twice and stores the returned references in member variables. The testUnique() method checks to see that the references are identical. Example 3 shows that test case output:

Example 3. Test case output

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 the preceding listing illustrates, Example 2's simple test passes with flying colors—the two singleton references oBTained with ClassicSingleton.getInstance() are indeed identical; however, those references were obtained in a single thread. The next section stress-tests our singleton class with multiple threads.

Multithreading considerations

Tags:Simply Singleton part

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接