Source: "Agile Software Development: Principles, Patterns, and Practices" by Robert C. Martin. Available at www.objectmentor.com/PPP.

public class Singleton
{
	private static Singleton theInstance = null;
	private Singleton() {}
	
	public static Singleton Instance()
	{
		if (theInstance == null)
			theInstance = new Singleton();
		return theInstance;	
	}
}




import junit.framework.*;
import java.lang.reflect.Constructor;

public class TestSimpleSingleton extends TestCase
{
	public TestSimpleSingleton(String name)
	{
		super(name);
	}
	
	public void testCreateSingleton()
	{
		Singleton s = Singleton.Instance();
		Singleton s2 = Singleton.Instance();
		assertSame(s, s2);
	}
	
	public void testNoPublicConstructors() throws Exception
	{
		Class singleton = Class.forName("Singleton");
		Constructor[] constructors = singleton.getConstructors();
		assertEquals("Singleton has public constructors.", 0, constructors.length);
	}
}
Monostate:

public class Monostate
{
	private static int itsX = 0;
	public Monostate() {}
	
	public void setX(int x)
	{
		itsX = x;
	}
	
	public int getX()
	{
		return itsX;
	}
}



import junit.framework.*;

public class TestMonostate extends TestCase
{
	public TestMonostate(String name)
	{
		super(name);
	}
	
	public void testInstance()
	{
		Monostate m = new Monostate();
		for (int x = 0; x<10; x++)
		{
			m.setX(x);
			assertEquals(x, m.getX());
		}
	}
	
	public void testInstancesBehaveAsOne()
	{
		Monostate m1 = new Monostate();
		Monostate m2 = new Monostate();

		for (int x = 0; x<10; x++)
		{
			m1.setX(x);
			assertEquals(x, m2.getX());
		}
	}
}


This is an example from CSci 3601 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.