// Make AWS an interface that defines the operations it provides.
trait AWS {
def foo(...): IO[Unit]
}
// In the companion object put a factory method that instantiates the resources.
object AWS {
def instance(...): Resource[IO, AWS] =
Resource
.make(IO(AWSClientBuilder.defaultClient))(client => IO(client.close()))
.map(client => new AWSImpl(client))
}
// Have a private implementation of the interface.
private[pckg] final class AWSImpl (client: AWSClient) extends AWS {
def blah(...): IO[Unit] = IO {
client.submitJob(new AwsRequest(...))
}
}
// Whatever was using AWS globally before now must require its dependency.
final class Domain(aws: Aws) {
def bar(...): IO[Unit] =
aws.foo(...)
}
// Assembly the dependency graph on the main.
final class Main extends IOApp.Simple {
override final val run: IO[Unit] =
Aws.instance(...).use { aws =>
val domain = new Domain(aws)
domain.bar(...)
}
}
1条答案
按热度按时间goqiplq21#
从技术上讲不是,因为
client
(以及AWS) 是共享的可变状态。但是,重构不仅使用
Resource
,而且不使用全局对象,也不显式地向下传递依赖关系。就像这样:
这是一个很笼统的想法,不要盲从。