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
]
- Techniques after using Swift for a month posted by sstrader on 26 August 2015 at 11:41:51 PM
- Some thoughts on Ruby after finishing a week (minus one day) of training posted by sstrader on 15 December 2011 at 8:59:30 PM
- Links on the singleton pattern posted by sstrader on 9 December 2011 at 9:19:50 AM
- Phonebot posted by sstrader on 29 October 2011 at 6:37:05 PM
- The labeled break in Java posted by sstrader on 4 September 2011 at 11:27:56 AM
Related entries
Other entries categorized in Programming: