package chapter05
//单例设计模式
object Test11_Singleton {
def main(args: Array[String]): Unit = {
//val stu1 = new Student11("alice",20) //因为Student11被private修饰,所以不可以直接new对象
//stu1.showInfo()
val student1 = Student11.getInstance()
student1.showInfo()
println(student1)
val student2 = Student11.getInstance()
student2.showInfo()
println(student2)
}
}
class Student11 private(val name: String, val age: Int) {
def showInfo(): Unit = {
println(s"name: ${name} age: ${age} school: ${Student11.school}")
}
}
//饿汉模式:不管有没有直接new对象
//object Student11{
// val school : String = "henry"
//
// private val student : Student11 = new Student11("alice",20)
//
// def getInstance() : Student11 = {
// student
// }
//
//}
//懒汉模式:先判断有没有对象,如果没有则new
object Student11 {
val school: String = "henry"
private var student: Student11 = _
def getInstance(): Student11 = {
if (student == null) {
student = new Student11("alice", 20)
}
student
}
}```
结果:
name: alice age: 20 school: henry
chapter05.Student11@d041cf
name: alice age: 20 school: henry
chapter05.Student11@d041cf
解析:虽然上方我们创建了两个对象的实例,student1和student2;但是她们指向同一个地址:chapter05.Student11@d041cf
Scala单例模式(懒汉与饿汉)
最新推荐文章于 2022-08-24 22:17:16 发布