gpt4 book ai didi

java - 从另一个 DAOFactory 调用一个 DAO

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:33 25 4
gpt4 key购买 nike

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

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

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

这是我的例子:

enter image description here

主要头痛来自FooCloudDao从 API 加载数据。此 API 需要某种身份验证方法 - 登录期间存储的字符串 token (例如 Session 对象 - 是的,这也有自己的 DAO)。

只是传递一个 Session 很诱人实例通过FooDaoFactory ,以防万一没有联系,但这似乎很老套且违反直觉。接下来我能想到的是访问 SessionDAOFactory来自内部 FooDaoFactory获得 Session 的实例(然后在我需要 FooCloudDAO 实例时传递它)。

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

最佳答案

我认为您的问题实际上是 FooCloudDao 与其他组件具有不同的“依赖关系”,您希望避免在途中将依赖关系传递给每个类。

尽管有相当多的设计模式可以解决您的问题,但我还是建议您看一下依赖注入(inject)/控制反转 原则和框架。你会用这个做什么:

  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 保持干净,不会通过
  • 传递依赖项
  • 您使您的代码更易于测试,因为您可以在没有真实 session 的情况下测试您的 FooCloudDao(您只能提供假接口(interface)实现)
  • 以及控制反转带来的所有其他好处...

关于 session 的注意事项:如果您遇到在 SessionBasedApiTokenProvider 中获取 session 的问题,大多数时候 session 本身也会注册到 IoC Controller ,并在需要的地方注入(inject)。

关于java - 从另一个 DAOFactory 调用一个 DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com