Friday, July 24, 2009

design pattern Singleton

  1. public class SimpleSingleton {
  2. private SimpleSingleton singleInstance = null;
  3. //Marking default constructor private
  4. //to avoid direct instantiation.
  5. private SimpleSingleton() {
  6. }
  7. //Get instance for class SimpleSingleton
  8. public static SimpleSingleton getInstance() {
  9. if(null == singleInstance) {
  10. singleInstance = new SimpleSingleton();
  11. }
  12. return singleInstance;
  13. }
  14. }
in multi-thread environment, please use:

public static synchronized SimpleSingleton getInstance() { }


No comments:

Post a Comment