이 해결책은 다소 복잡하지만, 자신을 반복하지 않도록한다.
REPL에서 코드를 확인할 수는 없지만 아이디어를 제공해야합니다.
/************************************************
* This part is used once
************************************************/
//We define a request-transforming type
type Configuration = Request => Request
/* now we prepare configuration selectively based on a flag
* the function is curried to store different configurations
* once, leaving the flag to be defined only as we actually
* prepare the request.
* Note that a false flag will give back the identity function
* from Predef that leaves the argument untouched
*/
def configuring(conf: Configuration)(flag: boolean) =
if (flag) conf else identity
//The available configuration types, wrapping the "fluent" calls
val secured_?: Boolean => Configuration = configuring(_.withSecurity)
val throttled_? = configuring(_.withThrottling)
val pooled_? = configuring(_.withPooling)
/************************************************
* This part is used each time we need
* to configure a request
************************************************/
val req = Request()
/* prepare a sequence of configurations
* and compose them sequentially
*/
def configurations: Configuration = Seq(
secured_?(needSecurity),
throttled_?(needThrottling),
pooled_?(needPooling)
).reduce(_.compose(_))
/* apply the combined configuring
* function to the new request
*/
val configured = configurations(req)
매개 변수로 플래그를 취할 것입니다 더 나은 인터페이스 것 같아 그래서 당신 수 만 할'req.withSecurity (needSecurity) .withThrottling (needThrottling) .withPooling (needPooling)'. – michaelsnowden
저는 외부 라이브러리에 대해 대부분 염려하고 있습니다 – synapse
네가 나쁜 제 3 자 디자인을 바꿀 수 없다는 것은 유감입니다. – michaelsnowden