5 January 2010

Singleton for Java

Abstract generic class to use when you need class-level singletons (i.e. everyone's favorite factory pattern):

public abstract class Singleton<T> {

	protected T t;

	protected abstract T init();

	public T get() {
		if (t == null) {
			t = init();
		}
		return t;
	}

	public void clear() {
		t = null;
	}

}

Simple use:

public class MyClass {

	protected Singleton<MyResource> myResource = new Singleton() {

		@Override
		protected MyResource init() {
			return new MyResource();
		}

	};

	public void doWork() {
		myResource.get().doWorkOnResource();
	}

}
[ posted by sstrader on 5 January 2010 at 11:03:02 PM in Programming ]