用单例对象实现单例模式

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{}

  

猜你喜欢

转载自www.cnblogs.com/wanfeng1937/p/10064060.html
今日推荐