作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
当存在循环关系时,如何获得一组类的类型安全性。我有 3 个类,路由器、交互器和组件,这样
abstract class Router<C extends Component, I extends Interactor>
abstract class Interactor<R extends Router>
abstract class Component<I extends Interactor>
我想确保特定的路由器绑定(bind)到特定的组件和特定的交互器。
编辑 应用程序的架构确保我们为 1 个组件的 1 个交互器提供了 1 个路由器。一些重用是可能的,但如果路由器 A 与交互器 A 和组件 A 一起使用,它将始终是这样,否则我们将定义路由器 B 与交互器 A 和组件 B。
编辑2 一个更具体的例子:我们可以拥有包含 loginscreenrouter、loginscreeninteractor 和 loginscreencomponent 的登录屏幕,然后是具有相同结构的另外 3 个类的加载屏幕。但我们不希望开发人员不小心将 loadingscreeninteractor 传递给 loginscreenrouter
最佳答案
每个类型都需要一个参数来表示每个类型,包括它自己。
abstract class Router<
R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
> { }
abstract class Interactor<
R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
> { }
abstract class Component<
R extends Router<R,C,I>, C extends Component<R,C,I>, I extends Interactor<R,C,I>
> { }
我想另一种我以前从未见过的方法是将所有交互都归为一种类型。更少的角度,但感觉不是很 OO,可能会导致更多工作。
import java.util.Set;
interface System<R extends Router, C extends Component, I extends Interactor> {
Set<R> routers(I interactor);
Set<R> routers(C component);
Set<I> interactors(R router);
Set<I> interactors(C component);
Set<C> components(R router);
Set<C> components(I interactor);
}
abstract class Router {}
abstract class Interactor {}
abstract class Component { }
关于Java 循环泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54047280/
我是一名优秀的程序员,十分优秀!