Scala 单例对象 && 伴生类

8 阅读2分钟

单例对象

用 object 关键字来创建一个单例对象。
单例对象:只有一个 不能被new ,适用于存放工具方法 常量

格式:

//  object 对象名 {
//    属性;
//    方法....
//  }

代码演示:

object Mytool {
  // 属性
  val PI = 3.14

  // 方法
  def Area(r:Double):Double = {
    PI * r * r
  }
}

def main(args: Array[String]): Unit = {
  // 对象.属性名
  // 对象.方法名

  println( Mytool.PI)  // 3.14
  println( Mytool.Area(10) ) // 314
}

1. 通过object关键字创建的是一个对象,不是一个类型。

2. 不能使用new关键字:声明单例对象的时候不可以使用new关键字。

3. 不能传递参数:单例对象无法传递参数。

伴生类

当同名的类和单例对象在同一个源码文件时,这个类称为单例对象的伴生类,对象称为类的伴生对象

伴生类 和 伴生对象: 1. 类和对象同名 2. 在一个文件中

  • 类就是伴生类 对象就是伴生对象
  • 特点:可以相互访问对象的私有成员

代码演示(访问私有方法):

class Student() {
  // private 修饰的属性 无法在类的外部被访问!
   private val hobby = "打游戏"
}

object Student {
  def introduce(stu: Student): Unit = {
    println(s"我的爱好是:${stu.hobby}")
  }
}

def main(args: Array[String]): Unit = {
  val stu1 = new Student()
  // syu1.hobbby  // 无法访问私有属性

  Student.introduce(stu1)
}
  1. 类名和对象名必须同名。
  2. 必须在同一个源码文件中。

Scala的伴生对象和伴生类的特点:伴生对象和类的私有private成员可以相互访问。

单例模式

  • 伴生类和伴生对象 实现一种特殊的编程的模式:单列模式
  • 单列模式:让一个类只能有一个实例对象 一个类只能被 new 一次!
  • 特点:可以相互访问对象的私有成员
// 1.把构造函数设置为private
  class Student private() {
}

// 2.伴生对象中 访问private
object Student {
  private val instance = new Student() // 在伴生对象中可以访问private修饰的构造器

  def getInstance(): Student = {
    instance
  }
}

def main(args: Array[String]): Unit = {
  //val stu1 = new Student()
  //val stu2 = new Student()
  //println(stu1 = =stu2) // false

  val stu1 = Student.getInstance()
  val stu2 = Student.getInstance()

  println(stu1 == stu2) //true
}