1.伴生类和伴生对象,实现单例模式:一个类只能有一个对象!
1.让构造函数变成私有 在类的外部,就不能通过new来创建对象。
2.在伴生对象中创建的实例 并返回。
object a1103 {
/* 伴生类 和 伴生对象 实现 单例模式:一个类只能有一个对象!
*/
// 1.让构造函数变成私有 在类的外部,就不能通过new来创建对象
class Student() {
//private 修饰的属性 在类的外部(在当前的class之外) 无法访问!
private val name:String = "小花"
}
// 2.在伴生对象中创建的实例 并返回
object Student {
val instance = new Student() // 在伴生对象中 可以访问伴生类的私有成员
def getInstance:Student = {
instance
}
}
def main(args: Array[String]): Unit = {
val stu1 = Student.getInstance
val stu2 = Student.getInstance
println(stu1 == stu2)
//运行结果
true
}