Java循环泛型

时间:2019-01-04 22:57:41

标签: java generics

当存在循环关系时,如何获得一组类的类型安全性。我有3个类,分别是Router,Interactor和Component

abstract class Router<C extends Component, I extends Interactor>
abstract class Interactor<R extends Router>
abstract class Component<I extends Interactor>

我想确保将特定路由器绑定到特定组件和特定交互器。

编辑该应用程序的体系结构可确保我们只有1个路由器用于1个组件的1个交互器。某些重用是可能的,但是如果路由器A与交互器A和组件A始终保持这种方式,那么例如,我们将路由器B与交互器A和组件B定义在一起。

编辑2 一个更具体的示例: 我们可以拥有一个包含登录屏幕路由器,登录屏幕交互器和登录屏幕组件的登录屏幕,然后是具有相同结构中的另外3个类的加载屏幕。但是我们不希望开发人员意外将loadingscreeninteractor传递给loginscreenrouter

1 个答案:

答案 0 :(得分:8)

每种类型(包括自身)都需要一个参数。

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 { }