class Man private(val sex: String, name: String){
def describe = { println("Sex:" + sex + "name:" + name) } } object Man{ var instance: Man = null def apply(name: String)={ if(instance == null){ instance = new Man("男", name) } instance } }
對象構造器在該對象第一次使用時調用。若是對象沒有使用過,他的構造器不會被執行。app
對象基本具備類的全部特性,就是一點,你不能設置構造器的參數。 測試
測試:spa
val man1 = Man("Nick") val man2 = Man("Thomas") man1.describe man2.describe
class Account {
val id = Account.newUniqueNumber() private var balance = 0.0 def deposit(amount: Double) { balance += amount } def description = "Account " + id + " with balance " + balance } object Account { // The companion object private var lastNumber = 0 private def newUniqueNumber() = { lastNumber += 1; lastNumber } }
測試:code
val acct1 = new Account
val acct2 = new Account acct1.deposit(1000) val d1 = acct1.description val d2 = acct2.description
尖叫提示:對象
1)apply 方法通常都聲明在伴生類對象中,能夠用來實例化伴生類對象:blog
class Man private(val sex: String, name: String){
def describe = { println("Sex:" + sex + "name:" + name) } } object Man{ def apply(name: String)={ new Man("男", name) } }
測試:ip
val man1 = Man("Nick")
val man2 = Man("Thomas") man1.describe man2.describe
2)也能夠用來實現單例模式,咱們只須要對上述例子稍加改動:it
看上面 8.1 單例模式
object Hello {
def main(args: Array[String]) {
println("Hello, World!") } }
或者擴展一個App特徵:io
object ObjectSyllabus extends App{
if(args.length > 0) println("hello," + args(0)) else println("hello,world!") }
object TrafficLightColor extends Enumeration {
val Red = Value(0, "Stop") val Yellow = Value(10) // Name "Yellow" val Green = Value("Go") // ID 11 }
測試:ast
println(TrafficLightColor.Red)
println(TrafficLightColor.Red.id)
println(TrafficLightColor.Red.toString)