设计模式遇到scala-工厂模式_factory
一旦参与实际项目,无论大小都一定会接触到工厂模式,Scala中如何阐释工厂模式呢。
Vehicle接口:trait Vehicle {
def drive
}
各种Vehicle实现:class Car extends Vehicle {
override def drive {
printf("car bibi~")
}
}
class Bus extends Vehicle {
override def drive {
printf("bus didi~")
}
}
class Truck extends Vehicle {
override def drive {
printf("truck wowo~")
}
}
重点来了,工厂:object Vehicle {
def apply(kind: String) = kind match {
case "car" = new Car()
case "bus" = new Bus()
case "truck" = new Truck()
}
}
工厂是object,至于工厂方法的名字当然也可以按照Java中的习惯,叫做getInstance,newInstance,valueOf等等经典名字,但是Scala中用apply还有另外一个优点,就是Vehicle.apply(“car”)中可以省略.apply,直接调用Vehicle(“car”),这是Scala追求的简洁美之一。
测试代码:object Test extends App {
val myVehicle = Vehicle("car")
myVehicle drive //car bibi~
}