从另一个 DAOFactory 调用一个 DAO

Calling one DAO from another DAOFactory

目前,我的应用程序架构流程如下:

View → Presenter → Some asynchronous executor → DAOFactory → DAO (interface) → DAO (Impl)

就目前而言,这种架构是可行的;主要是因为我目前只需要一种 DAO。但随着需求的增长,我需要扩展到多个 DAO,每个 DAO 都有自己关于如何获取数据的实现。

这是我的案例的一个例子:

最头疼的是 FooCloudDao,它从 API 加载数据。这个 API 需要某种身份验证方法 - 一个在登录期间存储的字符串令牌(例如,一个 Session 对象 - 是的,它也有自己的 DAO)。

很想通过 FooDaoFactory 传递一个 Session 实例,以防万一没有连接,但这看起来很老套而且违反直觉。我可以想象的下一件事是从 FooDaoFactory 中访问 SessionDAOFactory 以获得 Session 的实例(然后在我需要 FooCloudDAO 实例时传递它)。

但正如我所说,我不确定我是否可以做这样的事情 - 好吧,也许我 可以 ,但这是 真的正确的做法吗?

我认为你的问题实际上是 FooCloudDao 与其他组件有不同的 "dependencies",你想避免在途中通过每个 class 传递依赖项。

虽然有很多设计模式可以解决您的问题,但我建议您看一下 Dependency Injection / Inversion of Control 原则和框架。你会用这个做什么:

  1. You would create an interface for what your FooCloudDao needs, for example:
interface ApiTokenProvider {
     string GetToken();
 }
  1. You would create and implementation of that interface which would get it from the session or wherever that thing comes from:
class SessionBasedApiTokenPrivider implements ApiTokenProvider {
    public string GetToken() {
        // get it from the session here
    }
}
  1. The defined class above would need to be registered with IoC container of your choice as the implementation of ApiTokenProvider interface (so that whoever asks for ApiTokenProvider will be decoupled from the actual implementation -> the container would give him the proper implementation).

  2. You would have something called constructor injection on your FooCloudDao class (this is later used by the container to "inject" your dependency):

public FooCloudDao(ApiTokenProvider tokenProvider) {
    // store the provider so that the class can use it later where needed
}
  1. Your FooDaoFactory would use the IoC container to resolve the FooCloudDao with all its dependencies (so you would not instantiate the FooCloudDao with new)

执行这些步骤时,您将确保:

  • FooDaoFactory 不会通过
  • 传递依赖项
  • 你使你的代码更易于测试,因为你可以在没有真实会话的情况下测试你的 FooCloudDao(你只能提供假接口实现)
  • 以及控制反转带来的所有其他好处...

关于session的注意事项:如果在SessionBasedApiTokenProvider中遇到获取session的问题,大部分时候session本身也会注册到IoC控制器,并在需要的地方注入。