1. 程式人生 > >用單例物件實現單例模式

用單例物件實現單例模式

2018-12-04 14:55:07

object SingletonDemo { //object修飾的為物件
  def main(args: Array[String]): Unit = {

    val s = SessionFactory
    println(s.getSession)
    println(s.getSession.size)
    println(s.removeSession)
    println(s.getSession.size)

  }
}

object SessionFactory {
  println("SessionFactory被執行")

  var i = 5 // 計數器

  // 存放Session物件的陣列
  val sessions = new ArrayBuffer[Session]()

  // 向sessions裡新增Session物件,最多新增5個Session物件
  while (i > 0){
    println("while被執行")
    sessions.append(new Session)
    i -= 1
  }

  // 獲取Session物件
  def getSession = sessions

  // 刪除Session物件
  def removeSession {
    val session = sessions(0)
    sessions.remove(0)
    println("session物件被移除" + session)
  }

}

class Session{}