code_junkie

Singleton Factory method

Nov 12th, 2011
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. /**
  2. * An interface defining objects that can create Singleton
  3. * instances.
  4. */
  5. public interface SingletonFactoryFunctor {
  6. /**
  7. * @return An instance of the Singleton.
  8. */
  9. public Singleton makeInstance();
  10. }
  11.  
  12. public static synchronized Singleton getInstance()
  13. {
  14. // since whole method is synchronized only 1 thread can
  15. // enter the following block ensuring only one instance
  16. // is ever created. however we pay a synchronization
  17. // penalty every time this method is called.
  18. if(mInstance==null) {
  19. mInstance=new Singleton();
  20. }
  21. return mInstance;
  22. }
  23.  
  24. // no synchronization penalty, but penalty for eager init
  25. private static Singleton mInstance = new Singleton();
  26.  
  27. public static Singleton getInstance()
  28. {
  29. return mInstance;
  30. }
  31.  
  32. private volatile static Singleton mInstance;
  33.  
  34. private Singleton(){}
  35.  
  36. public static Singleton getInstance()
  37. {
  38. if(mInstance==null) {
  39. synchronized (Singleton.class) {
  40. // only pay synchronization penalty once
  41. if(mInstance==null){
  42. mInstance=new Singleton();
  43. }
  44. }
  45. }
  46. return mInstance;
  47. }
  48.  
  49. public class Singleton {
  50.  
  51. private static Singleton mInstance;
  52.  
  53. private Singleton(){}
  54.  
  55. public static Singleton getInstance()
  56. {
  57. if(mInstance==null){
  58. mInstance=new Singleton();
  59. }
  60. return mInstance;
  61. }
  62.  
  63. }
Add Comment
Please, Sign In to add comment