Groovy singleton pattern

Q1. What is the best way to implement a singleton pattern with groovy? What are the other options available in groovy to support the singleton mechanism?

Any example that would be helpful.

Q2. Does groovy support something like File changed listener?

+5
source share
2 answers

Q1

You can make any class singleton simple by adding the @Singleton annotation (since groovy v 1.7.0 is at least):

@Singleton
class MyClass {

}

Then you can access the singleton instance with

MyClass singleton = MyClass.instance

Q2

, , groovy , , ? Groovy. , Java ( groovy).

+15

Q2: groovy , Java 7, groovy, .

, foo , - :

import java.nio.file.*
FileSystems.default.getPath(".")  // dot for current directory
def watchKey = p.register(FileSystems.default.newWatchService(),
    StandardWatchEventKinds.ENTRY_MODIFY)
def events = watchKey.pollEvents()
events.findAll{it.context().fileName == 'foo'}.each { event ->
    println "foo was changed"
}
+7

All Articles