Scala 入门笔记-单例对象

拟墨画扇 提交于 2019-12-23 12:50:21

在Scala中实现静态字段和静态方法的方式是用Object关键字来实现

1.工具类,存放常量和工具方法

2.实现单例模式

 

package day03

import scala.collection.mutable.ArrayBuffer

object SingletonDemo {
  def main(args: Array[String]): Unit = {
    val sessionFactory = SessionFactory

    println(sessionFactory.getSession)
    println(sessionFactory.getSession.size)
    println(sessionFactory.removeSession)
  }
}

object SessionFactory {
  println("SessionFactory")

  var i = 5

  private val session = new ArrayBuffer[Session]

  while (i > 0) {
    session += new Session
    i -= 1
  }

  def getSession = session

  def removeSession : Unit = {
    session.remove(0)
    println("session " + session(0) + " remove")
  }
}

class Session {}

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!