anish
anish

Reputation: 7412

groovy singleton pattern

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

Any example that would be useful.

Q2. Does groovy support something like File changed listener?

Upvotes: 9

Views: 7813

Answers (2)

Dónal
Dónal

Reputation: 187349

Q1

You can make any class a singleton simply by adding a @Singleton annotation (since groovy v1.7.0 at least):

@Singleton
class MyClass {

}

You can then access the singleton instance with

MyClass singleton = MyClass.instance

Q2

I think you're asking if Groovy provides a listener which is called every time a file is changed? I am not aware of any such facility in Groovy. If such a class exists you're more likely to find a Java implementation (which you could use in your Groovy program).

Upvotes: 20

ataylor
ataylor

Reputation: 66069

Regarding Q2: while groovy itself doesn't provide any way to be notified on file changes, Java 7, which can be used with groovy, does.

In particular, if you want to watch for file changes on a file foo in the current directory, you can do something like this:

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"
}

Upvotes: 7

Related Questions