伴生类 和 伴生对象

35 阅读1分钟

伴生类 和 伴生对象

特点:

1.类和对象名

2.在一个文件中

3.可以互相访问对方的私有成员

注:类就是伴生类,对象就是伴生对象

level02-class06

eg:

class Student() {
    //private 修饰的属性,无法在类的外部被访问
    private val hobby = "打游戏"

  }

  object Student {
    def introduce(stu: Student): Unit = {
      println(s"我的爱好是:${stu.hobby}")//私有的
    }
  }

  def main(args: Array[String]): Unit = {
    val stu1 = new Student()
    //stu1.hobby  //无法访问私有属性

    Student.introduce(stu1)
  }
}

单例模式

1.伴生类和伴生对象,实现一种特殊的编程的模式

2.特点:可以相互访问对方的私有成员

class Student private() {

  }

  //2.伴生对象中,访问private
  object Student {
    private val instance = new Student()

    def getInstance(): Student = {
      instance
    }
  }
  def main(args: Array[String]): Unit = {
    //无法通过new来创造对象!
    //val stu1 = new Student()
    //val stu2 = new Student()
    //println(stu1 == stu2) //false
    val stu1 = Student.getInstance()
    val stu2 = Student.getInstance()

    println(stu1 == stu2)
  }
}

apply方法

1.在伴生对象中补充一个apply方法,这样创建对象的时候,就可以省略 new

2.伴生类名(参数)=====伴生对象名.apply(参数)

eg:

//日志
  class Logger (var filename:String){

  }

  object Logger {
    def apply(filename:String):Logger = {
      println("apply")
      new Logger(filename)
    }
  }
  def main(args: Array[String]): Unit = {
    //省略 new
    val log1 = Logger("test.log")
    println(log1.filename)
  }
}

伴生类和伴生对象 +apply 实现 单例 模式

eg:

//日志类
  class Logger (var filename:String){
  def log(message:String):Unit = {
    println(s"Log:$message")
    }
  }

  object Logger {
    private var instance:Option[Logger] = None
    def apply(filename:String):Logger = {
      if (instance.isEmpty) {
        instance = Some(new Logger(filename))
      }
      instance.get
    }
  }
  def main(args: Array[String]): Unit = {
    //省略 new
    val log1 = Logger("test.log")
    log1.log("2025-11-03 上午上课")
  }
}

将日志写入文件

运行时生成一份日志文件信息(test.log)

//日志类
  class Logger (var filename:String){

    def log(message:String):Unit = {
      //把日志相信写入到文件里
      val writer = new FileWriter(filename, true)
      writer.write(s"$message \n")
      println(s"Log: $message")
      writer.close()
    }
  }

  object Logger {
    private var instance:Option[Logger] = None
    def apply(filename:String):Logger = {
      if (instance.isEmpty) {
        instance = Some(new Logger(filename))
      }
      instance.get
    }
  }
  def main(args: Array[String]): Unit = {
    //省略 new
    val log1 = Logger("test.log")

    log1.log("2025-11-03 上午上课")
    log1.log("2025-11-05 运动会")
    log1.log("2025-11-07 周末")
  }
}