单例模式:一个类(class)中只有一个对象!
- 不让它new!把构造函数设置为私有的!
- 在伴生对象中调用new来生成一个对象,提供一个方法来获取这个对象
package level02
object class06 {
// 添加了private之后,构造函数在类的外部就不可访问!
class Student private (var name:String ,var age:Int) {
}
object Student {
// 在伴生对象中,可以访问伴生类的私有成员
private val ins = new Student("小花", 18)
def getInstance:Student = ins
}
def main(args: Array[String]): Unit = {
// val stu1 = new Student("小花", 18)
// val stu2 = new Student("小谷", 18)
val stu1 = Student.getInstance
val stu2 = Student.getInstance
println(stu1 == stu2)
}
}