scala 单例、伴生对象、伴生类

单例:使得对象成为系统中的唯一实例

package scala

object single {
  private var sno:Int = 3;
  def singlesno()={
    sno += 1
    sno
  }
}

object singleTest {
  def main(args: Array[String]): Unit = {
    println(single.singlesno())
    println(single.singlesno())
  }
}

伴生对象: 当单例对象与某个类共享同一个名称时,它就被称为是这个类的伴生对象(companion object)。类和它的伴生对象必须定义在同一个源文件中。类被称为是这个单例对象的伴生类(companion class)。类和它的伴生对象可以互相访问其私有成员

package scala

object associated {
  private var sno:Int = 3;
  def incrementSno()={
    sno += 1
    sno
  }
  
  def main(args: Array[String]): Unit = {
    println("单例对象:" + associated.incrementSno())
    val obj = new associated()
    obj.infoCompObj();
    
  }
}

class associated() {
  def infoCompObj() = println("伴生类中访问伴生对象:" + associated.sno)
}

 

posted on 2017-03-10 11:30  sunyaxue  阅读(264)  评论(0编辑  收藏  举报

导航