单例

1.懒汉式

package com.atguigui.bigdata.chapter06


object TestSingleTon {
  def main(args: Array[String]): Unit = {
    val singleTon = SingleTon.getInstance
    val singleTon1 = SingleTon.getInstance
    println(singleTon.hashCode()+ "  " + singleTon1.hashCode())
    println(singleTon == singleTon1)

  }
}

//构造方法私有化
class SingleTon private() {

}


object SingleTon {
  private var s: SingleTon = null

  def getInstance = {
    if (s == null) {
      s = new SingleTon
    }
  }
}


2.饿汉式

package com.atguigui.bigdata.chapter06


object TestSingleTon extends App {
  val singleTon = SingleTon.getInstance
  val singleTon2 = SingleTon.getInstance
  println(singleTon.hashCode() + " ~ " + singleTon2.hashCode())
  println(singleTon == singleTon2)
}
//将SingleTon的构造方法私有化
class SingleTon private() {
  println("~~~")
}
object SingleTon {
  private val s: SingleTon = new SingleTon
  def getInstance = {
    s
  }
}

你可能感兴趣的:(单例)