Singleton object in scala

everyone:

  it is good! Look at the code of scala to generate a singleton, and share it for reference only.

package day02

import scala.collection.mutable.ArrayBuffer

/**
  * 功能: 演示scala中的单例对象
  */
object SingletonDemo {
  def main(args: Array[String]) {
    //单例对象,不需要new,用【类名.方法】调用对象中的方法
    val session = SessionFactory.getSession()
    println(session)
    val session1 = SessionFactory.getSession()
    println(session1)
  }
}

object SessionFactory{
  //该部分相当于java中的静态块
  var counts = 5
  val sessions = new ArrayBuffer[Session]()
  while(counts > 0){
    sessions += new Session
    counts -= 1
  }

  //在object中的方法相当于java中的静态方法
  def getSession(): Session ={
    sessions.remove(0)
  }
}

class Session{

}

The running effect in idea is as follows:

As you can see, the sessions generated by the two sessions are not the same. Singleton verification succeeded

Explanation: 1 This is similar to using java's singleton factory to generate singletons. There are other methods. This is just a kind of

Guess you like

Origin blog.csdn.net/zhaoxiangchong/article/details/82184634