函数式编程中的策略模式

Strategy pattern in functional programming

我正在尝试使用 Java DZone 中提到的示例以函数式编程语言(不是纯函数式、没有对象、没有函数重载)编写策略设计模式示例。

虽然我知道很多功能都是在函数式编程语言中开箱即用的。

就设计模式概念而言,我是否遗漏了什么?

:是赋值运算符。

文件 FileCompressor

strategy:`noOp;

setCompressionAlgo:{[algo]
    strategy:algo
}

compressFiles:{[filesList]
    strategy[filesList]
 }

文件 ZipCompressor

zipCompress:{[fileList]
  //compress each file using the zip compression
 }

文件 RarCompressor

rarCompress:{[fileList]
  //compress each file using the rar compression
 }

文件客户端

start:{[path]
    filesList:getFiles[path];
    setCompressionAlgo[zipCompress];
    compressFiles[fileList]
 }

您通常不会将策略设置为全局(可变)变量。您可以将示例简化为

start: {[path]
    compressFiles: zipCompress;
    // change to
    // compressFiles: rarCompress
    // to use a different strategy

    // apply the strategy:
    compressFiles[fileList1]
    compressFiles[fileList2]
}