Ou Tsei
Ou Tsei

Reputation: 482

Scala singleton as instance of another class

I have a singleton object, that handles database stuff for my application, but I would like to have a similiar class to be used during testing, so that I can have many smaller test databases that dont interfere with each other.

I could just drop the singleton and just create a new instance of the database class at startup, but that would mean I'd have to pass around this instance to everywhere where database actions are needed and I dont want that.

I could make a singleton that would work as an interface to a single instance of the database class. Someting like this:

object DB{
    val db = new Database()
    def set(a:Int,b:Int) = db.set(a,b)
    def get(a:Int) = db.get(a)
}

This just feels sort of stupid and pointless, especially when the database class is fairly big and I'd have to do that to all of the methods. Is there a better way to solve this problem?

Thanks!

Upvotes: 2

Views: 572

Answers (2)

Daniel Langdon
Daniel Langdon

Reputation: 5999

Seems to me that your problem involves having multiple, different intances of a class, and being able to access them as a single object. For clarity, note that this things are kind of contradictory.

Hence, you need composition to have a reference to whatever actual instance you want to use. Then either you expose this instance directly (DB.instance.doSomething()) or take the effort of forwarding the API as you mention.

Seems to me you are not comfortable with either of these. If the syntax DB.instance bothers you, you can always put this instance in a package object and use it directly. You can also import DB._ to have direct access to the instance variable.

Upvotes: 0

alcarv
alcarv

Reputation: 899

The best way to accomplish that would be with a cake pattern, but you would have to indeed extend all the methods in your DB class.

In order to do that I would follow this article: http://www.warski.org/blog/2014/02/using-scala-traits-as-modules-or-the-thin-cake-pattern/

After you have created the cake pattern, you just have to have one trait that implements the "other DB" used for tests only on test source code. And, of course, the trait the implements the "real DB" on the main source code.

Upvotes: 2

Related Questions