gpt4 book ai didi

Java 循环泛型

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:23 25 4
gpt4 key购买 nike

当存在循环关系时,如何获得一组类的类型安全性。我有 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/

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