Reputation: 1498
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.
Upvotes: 10
Views: 6586
Reputation: 81
Not sure if this if this is what you're looking for but as the article explains, use the apply method without extending the base class
case class Foo(name:String)
object Foo { def apply(name:String) = new Foo(name) }
Upvotes: 0
Reputation: 21548
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.
Upvotes: 3
Reputation: 370102
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).
}
Upvotes: 15