You're here: Snippet Directory » Java (241)
Language:

Singleton

Language: English
Programming Language: Java
Published by: jacobbay [not registered]
Last Update: 5/15/2006
Views: 270


Description

A superclass for implementing the Singleton pattern, without the risk of being garbage collected.

Code

1 /** 2 * Class demonstrating the Singleton pattern 3 * realised in Java. 4 * According to the JVM specs the class should 5 * not be unloaded and the reference not garbage collected. 6 * 7 * Note that the class operation getInstance() also 8 * realises the "factory method" pattern, which means that this 9 * Singleton will care about creating the single instance. 10 * You can expand the pattern, implementing an abitrary 11 * factory method (for example if you want to pass parameters i.e. 12 * settings, configs etc.). 13 * 14 * Usage (from anywhere in your code, other classes): 15 * mySingleton.getInstance().myInstanceOperation(param1,param2,...); 16 * 17 * 18 * Reference: 19 * Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. 20 * 1995. Design Patterns. Addison-Wesley. Reading,Mass. 21 * 22 * @author Dieter Wimberger 23 */ 24 public class mySingleton { 25 26 private static mySingleton instance=null; 27 //... instance variables 28 29 /** 30 * Private constructor, so it cannot be 31 * instantiated from any other code. 32 */ 33 private mySingleton() { 34 //store single instance reference 35 instance=this; 36 //... abitrary initialisation 37 }//constructor 38 39 40 //... instance methods 41 42 43 /** 44 * Returns a reference to the singleton 45 * instance. 46 * 47 * @return the reference of the singleton instance. 48 */ 49 public static mySingleton getInstance() { 50 if(instance!=null) { 51 return instance; 52 } else { 53 return new mySingleton(); 54 } 55 }//getInstance 56 57 }//class mySingleton

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS