2013-06-18 82 views
0

我似乎有一个相对简单的问题:我确实有一些代码从http下载文件并执行解压缩操作。这2码似乎很类似:Scala - 分解构造函数

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 "); }) 
    } 

有没有办法改写的下载/解压方法到一个方法,并分解出constrcutors实现依赖 - 注入样的行为?

回答

0

我想你所问的问题是你的功能在开始和/或结束时具有相同需求的情况,但中间部分可以在每个呼叫的基础上有所不同。

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世界中的模板方法有关