一、什么是单例模式?
就是通过技术手段,让某个类只能有一个对象实例。这样做的好处就节约资源,能更加精准地管理。
二、讲授:
使用private来修饰构造器,这样在类的外部就无法访问了。在伴生对象中提供获取这个实例的入口方法。
编码示例:
class Student private() {
//private 修饰的属性,在类的外部(在当前的class之外)无法访问!
private val name:String = "小花"
}
object Student {
val instance = new Student() // 在伴生对象中,可以访问伴生类私有成员
def getInstance:Student = {
instance
}
}
def main(args:Array[String]): Unit = {
// val stu1 = new Student()
// val stu2 = new Student()
// val stu3 = new Student()
// val stu4 = new Student()
// stu1.name 是错误的,无法访问
val stu1 = Student.getInstance
val stu2 = Student.getInstance
println(stu1 == stu2) //true
}