How to Create a Singleton Class in Groovy

  • google plus

In Brief...

A singleton class in Groovy is a class that can only be instantiated one time. Traditionally this task has been accomplished by defining a class that has a private constructor and a method to return the instance of the class. Groovy provides an annotation, @Singleton, which simplifies the process.

To learn how to create a singleton class in Groovy, follow these 3 steps:

Instructions

  1. Open your text editor and type in the following Groovy statements:
    
    @Singleton
    class Arithmetic {
    	int add (int i, int j) {
    		return i+j;
    	}
    }	
    println "Result of calling add method: ${Arithmetic.instance.add(10, 20)}"
    // attempt instantiation
    try {
    	def arithmetic=new Arithmetic()	
    }
    catch (RuntimeException e) {
    	println("Runtime exception detected: ${e.message}")
    }	
    
    The program defines a class, Arithmetic, that contains a method named add. Note that the class is declared as a singleton class using the @Singleton annotation. Therefore only one instance of this class can be present in memory at any time. In addition, an instance property is available in order to reference the singleton instance. The add method is called using the instance property. Next, an attempt is made to instantiate the class and therefore create another instance of the class. At runtime, a RuntimeException will be raised. The program catches this exception and displays a message to the console.
  2. Save your file as SingletonClass.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run singleton class script
    The output shows the result of calling the add method using the instance property, followed by the output of the catch block. Therefore, a runtime exception did indeed occur when an attempt was made to instantiate the singleton class.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss