【问题标题】:Scala - factoring out constructorsScala - 分解构造函数
【发布时间】:2013-06-14 20:39:58
【问题描述】:

我似乎有一个相对简单的问题:我确实有一些从 http 下载文件并执行解压缩操作的代码。这两个代码看起来很相似:

  def downloadFile(url: URL, filename: String) {
    var out: OutputStream = null
    var in: InputStream = null

    try {
      val outPutFile = new File(filename)
      if (outPutFile.exists())
      {
        outPutFile.delete()
      }
      val uc = url.openConnection()
      val connection = uc.asInstanceOf[HttpURLConnection]
      connection.setRequestMethod("GET")
      in = connection.getInputStream()
      out = new BufferedOutputStream(new FileOutputStream(filename))

      copy(in, out)
    } catch {
      case e: Exception => println(e.printStackTrace())
    }

    out.close()
    in.close()

  }

    def unzipFile(file: File): String = {
    var out: OutputStream = null

    val outputFileName = "uncompressed" + file.getName()
    println("trying to acess " + file.getName() + file.getAbsoluteFile())
    val in = new BZip2CompressorInputStream(new FileInputStream(file))
    val outfile = new File(outputFileName)
    if (outfile.exists()) {
      outfile.delete()
    }
    out = new FileOutputStream(outputFileName)

    copy(in, out)
    in.close()
    out.close()
    return outputFileName

  }

     def copy(in: InputStream, out: OutputStream) {
    val buffer: Array[Byte] = new Array[Byte](1024)
    var sum: Int = 0
    Iterator.continually(in.read(buffer)).takeWhile(_ != -1).foreach({ n => out.write(buffer, 0, n); (sum += buffer.length); println(sum + " written to output "); })
  }

有没有办法将下载/解压缩方法重写为一个方法并分解构造函数以实现依赖注入的行为?

【问题讨论】:

    标签: scala closures


    【解决方案1】:

    我认为您要问的问题是您的函数对开始和/或结束有相同的需求,但中间部分可能因每次调用而异。如果这就是您正在寻找的,那么通过将中间部分作为这样的函数传递来解决该问题:

    def doSomething(func: => Unit){
      //Do common stuff here
    
      //Invoke passed in behavior
      func
    
      //Do common end stuff here
    }
    

    然后你可以像这样在另一个函数中使用它:

    def downloadFile(url: URL, filename: String) {
      doSomething{
        //You have access to url and filename here due to closure
      }
    }
    

    这样,如果这两个函数(downloadFileunzipFile)之间存在共同的问题/功能,您可以在 doSomething 中捕获它,然后只允许调用函数指定特定于该函数的行为.

    这个模式类似于贷款模式,也可能与OO世界的模板方法有关

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 2013-09-08
      • 2011-02-11
      • 2012-01-09
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多