伴生类+单例对象

87 阅读1分钟

一.创建对象

  1. class——>new
  2. 直接通过object来定义(单例对象,只有一个,孤单)
  3. 适用于数据的存储,提供一些工具方法,公用方法.....
object class07 {
  object Myschool {
    val name:String = "xxx学校"

    def say(): Unit = {
      println(s"say:${name}")
    }
  }

  def main(arges: Array[String]): Unit = {
    //对象名.属性名
    Myschool.name
    //对象名
  Myschool.say()
  }
}

二.伴生

  1. 类(class)和对象(object)同名,且在同一个文件中,此时他们互为伴生关系
  2. 此时,类->伴生类,对象->伴生对象
  3. 特点:可以相互访问对方的,私有(private)成员
object class08 {
 class Student(private val password:String) {
   private def validatePassword(input:String):Boolean = {
     input == password
   }
  }
  object Student {
    def check(stu:Student,pwd:String):Boolean = {
      //在伴生对象的内部,可以访问类的private成员
      stu.validatePassword(pwd)
    }
  }
  def main(arges:Array[String]): Unit={
    val stu1 = new Student("12345")
    if (Student.check(stu1,"12345")){
      println("验证通过")
    }
    //在类的外部,无法访问类的privte成员
//    if (stu1.validatePassword("12345")){
//      println("验证通过")
    } 
}

三.单例模式

  1. 单例模式:一个类(class)只能有一个对象!
  2. new 会自动调用 构造 函数?
  3. 步骤:
  • 不让它new,把构造函数设置为私有的!
  • 在伴生对象中调用new来生成一个对象;提供一个方法来获取这个对象
  • 在伴生对象中调用new来生成一个对象;提供一个方法来获取这个对象 */
object class09 {
//添加了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 = Student.getInstance
    val stu2 = Student.getInstance

    println(stu1 == stu2)
  
  }
}

例题

任务 1 中,object Circle是单例对象,直接通过对象调用方法即可完成圆周长和面积的计算。
object Circle {
  private val PI = 3.14

  // 计算圆的周长:2 * π * r
  def calculatePerimeter(radius: Double): Double = {
    2 * PI * radius
  }

  // 计算圆的面积:π * r²
  def calculateArea(radius: Double): Double = {
    PI * radius * radius
  }
}

// 测试
object TestCircle {
  def main(args: Array[String]): Unit = {
    val radius = 5.0
    println(s"半径为${radius}的圆,周长为${Circle.calculatePerimeter(radius)},面积为${Circle.calculateArea(radius)}")
  }
}
任务 2 通过 ** 伴生类(私有构造)+ 伴生对象(提供单例实例创建方法)** 实现单例模式,将圆的半径封装在伴生类中,通过伴生对象的getInstance方法控制对象的创建,保证单例特性的同时,也能灵活传入半径参数。
// 伴生类
class Circle private (private val radius: Double) {
  private val PI = 3.14

  def calculatePerimeter: Double = {
    2 * PI * radius
  }

  def calculateArea: Double = {
    PI * radius * radius
  }
}

// 伴生对象(实现单例模式)
object Circle {
  // 对外提供获取单例对象的方法(可根据需求调整半径参数)
  def getInstance(radius: Double): Circle = {
    new Circle(radius)
  }
}

// 测试
object TestCircle {
  def main(args: Array[String]): Unit = {
    val circle = Circle.getInstance(5.0)
    println(s"圆的周长为${circle.calculatePerimeter},面积为${circle.calculateArea}")
  }
}