单例:希望某个类只存在一个使用的对象,而不管有多少个调用者在使用它,就是单例的概念。
package base
object Singleton extends App {
val aloneC1 = AloneObj.getAloneCInstance
val aloneC2 = AloneObj.getAloneCInstance
aloneC1.addOne
aloneC2.addOne
println(aloneC1.getPrice, aloneC2.getPrice)
}
object AloneObj {
private var aloneC: AloneC = null
def getAloneCInstance: AloneC = {
// 第一次掉用时创建实例
if (this.aloneC == null) this.aloneC = new AloneC()
this.aloneC
}
}
// 需要单例的类
class AloneC {
private var price = 0.0
def addOne = {
price += 1
}
def add(num: Double): Unit = {
price += num
}
def getPrice = price
}