class08

18 阅读1分钟
object class08 {
  /**
   * 伴生类和伴生对象 +apply 实现 单例 模式
   *
   * 在伴生对象中补充一个apply方法,这样创建对象的时候,就可以省略 new
   * 伴生类名(参数)===== 伴生对象名.apply(参数)
   */
  //·日志类
  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 上午上课")

  }
}
```
```