开发者

groovy singleton pattern

开发者 https://www.devze.com 2023-04-09 22:33 出处:网络
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?

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 exa开发者_如何学运维mple that would be useful.

Q2. Does groovy support something like File changed listener?


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).


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号