应用-单例模式
什么是单例模式?
就是通过技术手段,让某个类只能有一个对象实例。这样做的好处就节约资源,能更加精准地管理。
使用private来修饰构造器,这样在类的外部就无法访问了。在伴生对象中提供获取这个实例的入口方法。
代码演示:
object practice38 {
/*
* 伴生类 和 伴生对象 实现 单例模式:一个类只能有一个对象!
*
* */
// 1. 让构造函数变成私有的。在类的外部,就无能通过new来创建对象了
class Student private () {
// 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 = new Student()
// val stu2 = new Student()
// val stu3 = new Student()
// val stu4 = new Student()
val stu1 = Student.getInstance
val stu2 = Student.getInstance
println(stu1 == stu2)