My design incorporates a small database abstraction, whereby I implement each database as a Singleton (well, an object
), with custom methods on the database for the couple of operations the code calls (it's mainly a log parser, dumping interesting statistics to a database).
I'd like to construct the Singleton database classes if possible, such that at runtime, each is constructed with config values (and those values remain constant for the remainder of the program's runtime). This would allow me to better test the code too (as I can mock the databases using Mockito or some such).
I'm still only learning Scala, but it seems there's no way to attach a constructor to a Singleton, and would appreciate any input on this problem - is there a better way to do what I'm doing? Is there some preferred way of constructing a Singleton?
Cheers in advance for any help.
Just put the constructor code in the body of the object definition:
object Foo {
println("Hello") // This will print hello the first time
// the Foo object is accessed (and only
// that once).
}
Rather than use a singleton (which is hard to test).. Whoever's creating the actors could create a database session factory and pass it to each actor, then it's still shared... and testable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With