Before I show you the DB class used in the previous example, let’s explore Scala objects. Scala doesn’t provide any static modifier, and that has to do with the design goal of building a pure object-oriented language where every value is an object, every operation is a method call, and every variable is a member of some object. Having static doesn’t fit well with that goal, and along with that there are plenty of downsides to using static in the code. Instead, Scala supports something called Singleton objects. A singleton object allows you to restrict the instantiation of a class to one object. Implementing a singleton pattern in Scala is as simple as the following:
- object RichConsole {
- def p(x: Any) = println(x)
- }
You can import and use all the members of the RichConsole object as follows:
The DB object introduced in listing 3.2 is nothing but a factory to create DB instances representing a database in MongoDB:
- object DB {
- def apply(underlying: MongDB) = new DB(underlying)
- }
The Factory pattern in Scala
Inside the apply method you’re creating an instance of the DB class. In Scala, both a class and an object can share the same name. When an object shares a name with a class, it’s called a companion object, and the class is called a companion class. Now the DB.scala file looks like the following:
- package ch3
- import com.mongodb.{DB => MongoDB}
- class DB private(val underlying: MongoDB) {
- }
- object DB {
- def apply(underlying: MongoDB) = new DB(underlying)
- }
In MongoDB, a database is divided into multiple collections of documents. Shortly you’ll see how you can create a new collection inside a database, but for now add a method to retrieve all the collection names to the DB class:
- package ch3
- import com.mongodb.{DB => MongoDB}
- import scala.collection.convert.Wrappers._
- class DB private(val underlying: MongoDB) {
- def collectionNames = for(name <- nbsp="" span="">new JSetWrapper(underlying.getCollectionNames)) yield name ->
- }
- ...
- import com.scalainaction.mongo._
- def client = new MongoClient
- def db = client.createDB("mydb")
- for(name <- db.collectionnames="" name="" nbsp="" println="" span="">->
- Listing 3.3 Completed MongoClient.scala
- package ch3
- import com.mongodb.Mongo
- class MongoClient(val host:String, val port:Int) {
- require(host != null, "You have to provide a host name")
- private val underlying = new Mongo(host, port)
- def this() = this("127.0.0.1", 27017)
- def dropDB(name:String) = underlying.dropDatabase(name)
- def createDB(name:String) = DB(underlying.getDB(name))
- def db(name:String) = DB(underlying.getDB(name))
- }
- Listing 3.4 DB.scala
- package ch3
- import com.mongodb.{DB => MongoDB}
- import scala.collection.convert.Wrappers._
- class DB private(val underlying: MongoDB) {
- def collectionNames = for(name <- nbsp="" span="">new JSetWrapper(underlying.getCollectionNames)) yield name ->
- }
- object DB {
- def apply(underlying: MongoDB) = new DB(underlying)
- }
沒有留言:
張貼留言