Scala (2): Factory Pattern

Vehicle Interface:

 trait Vehicle {
  def drive
}

Various implement of Vehicle:

  class Car extends Vehicle {
     override def drive {
       println("car comming")
     }
  }
class Bus extends Vehicle {
  override def drive {
    println("bus comming")
 }
}
class Truck extends Vehicle {
  override def drive {
    println("truck comming")
 }
}
The most important Thing is below:
 object Vehicle {
  def apply(kind: String) = kind match {
   case "car" = new Car()
   case "bus" = new Bus()
   case "truck" = new Truck()
  }
}
The factory is object, Scala uses “apply” because we can ignore .apply when call Vehicle. We only use Vehicle(“car”) to replace Vehicle.apply(“car”). This is the beauty of Scala. apply methods give us a nice syntactic sugar for when a class or object has one main use.
Test case:
object Test extends App {
  val myVehicle = Vehicle("car")
  myVehicle drive  //car coming
}

apply

When your class or object has main function, “apply” provides a good syntax candy.

class Foo {}
object FooMaker {
  def apply() = new Foo
}
val newFoo = FooMaker() // Here it looks like to call a function to instantiate an object. 

Or

class Bar {
  def apply() = 0
}
val bar = new Bar
bar() // output: Int = 0
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s